efl/src/lib/ecore/ecore_exe.c

1918 lines
60 KiB
C
Raw Normal View History

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#ifdef HAVE_SYS_PRCTL_H
# include <sys/prctl.h>
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#include "Ecore.h"
#include "ecore_private.h"
/* FIXME: Getting respawn to work
*
* There is no way that we can do anything about the internal state info of
* an external exe. The same can be said about the state of user code. User
* code in this context means the code that is using ecore_exe to manage exe's
* for it.
*
* Document that the exe must be respawnable, in other words, there is no
* state that it cannot regenerate by just killing it and starting it again.
* This includes state that the user code knows about, as the respawn is
* transparent to that code. On the other hand, maybe a respawn event might
* be useful, or maybe resend the currently non existent add event. For
* consistancy with ecore_con, an add event is good anyway.
*
* The Ecore_exe structure is reused for respawning, so that the (opaque)
* pointer held by the user remains valid. This means that the Ecore_Exe
* init and del functions may need to be split into two parts each to avoid
* duplicating code - common code part, and the rest. This implies that
* the unchanging members mentioned next should NEVER change.
*
* These structure members don't need to change -
* __list_data - we stay on the list
* ECORE_MAGIC - this is a constant
* data - passed in originally
* cmd - passed in originally
* flags - passed in originally
*
* These structure members need to change -
* tag - state that must be regenerated, zap it
* pid - it will be different
* child_fd_write - it will be different
* child_fd_read - it will be different
* child_fd_error - it will be different
* write_fd_handler - we cannot change the fd used by a handler, this changes coz the fd changes.
* read_fd_handler - we cannot change the fd used by a handler, this changes coz the fd changes.
* error_fd_handler - we cannot change the fd used by a handler, this changes coz the fd changes.
*
* Hmm, the read, write, and error buffers could be tricky.
* They are not atomic, and could be in a semi complete state.
* They fall into the "state must be regenerated" mentioned above.
* A respawn/add event should take care of it.
*
* These structure members need to change -
* write_data_buf - state that must be regenerated, zap it
* write_data_size - state that must be regenerated, zap it
* write_data_offset - state that must be regenerated, zap it
* read_data_buf - state that must be regenerated, zap it
* read_data_size - state that must be regenerated, zap it
* error_data_buf - state that must be regenerated, zap it
* error_data_size - state that must be regenerated, zap it
* close_write - state that must be regenerated, zap it
*
* There is the problem that an exe that fell over and needs respawning
* might keep falling over, keep needing to be respawned, and tie up system
* resources with the constant respawning. An exponentially increasing
* timeout (with maximum timeout) between respawns should take care of that.
* Although this is not a "contention for a resource" problem, the exe falling
* over may be, so a random element added to the timeout may help, and won't
* hurt. The user code may need to be informed that a timeout is in progress.
*/
struct _Ecore_Exe
{
EINA_INLIST;
ECORE_MAGIC;
pid_t pid;
void *data;
char *tag, *cmd;
Ecore_Exe_Flags flags;
Ecore_Fd_Handler *write_fd_handler; /* the fd_handler to handle write to child - if this was used, or NULL if not */
Ecore_Fd_Handler *read_fd_handler; /* the fd_handler to handle read from child - if this was used, or NULL if not */
Ecore_Fd_Handler *error_fd_handler; /* the fd_handler to handle errors from child - if this was used, or NULL if not */
void *write_data_buf; /* a data buffer for data to write to the child -
* realloced as needed for more data and flushed when the fd handler says writes are possible
*/
int write_data_size; /* the size in bytes of the data buffer */
int write_data_offset; /* the offset in bytes in the data buffer */
void *read_data_buf; /* data read from the child awating delivery to an event */
int read_data_size; /* data read from child in bytes */
void *error_data_buf; /* errors read from the child awating delivery to an event */
int error_data_size; /* errors read from child in bytes */
int child_fd_write; /* fd to write TO to send data to the child */
int child_fd_read; /* fd to read FROM when child has sent us (the parent) data */
int child_fd_error; /* fd to read FROM when child has sent us (the parent) errors */
int child_fd_write_x; /* fd to write TO to send data to the child */
int child_fd_read_x; /* fd to read FROM when child has sent us (the parent) data */
int child_fd_error_x; /* fd to read FROM when child has sent us (the parent) errors */
Eina_Bool close_stdin : 1;
int start_bytes, end_bytes, start_lines, end_lines; /* Number of bytes/lines to auto pipe at start/end of stdout/stderr. */
Ecore_Timer *doomsday_clock; /* The Timer of Death. Muahahahaha. */
void *doomsday_clock_dead; /* data for the doomsday clock */
Ecore_Exe_Cb pre_free_cb;
};
2006-04-05 18:16:02 -07:00
/* TODO: Something to let people build a command line and does auto escaping -
*
* ecore_exe_snprintf()
*
* OR
*
* cmd = ecore_exe_comand_parameter_append(cmd, "firefox");
* cmd = ecore_exe_comand_parameter_append(cmd, "http://www.foo.com/bar.html?baz=yes");
* each parameter appended is one argument, and it gets escaped, quoted, and
* appended with a preceding space. The first is the command off course.
2006-04-05 18:16:02 -07:00
*/
struct _ecore_exe_dead_exe
{
pid_t pid;
char *cmd;
};
static inline void _ecore_exe_exec_it(const char *exe_cmd,
Ecore_Exe_Flags flags);
static Eina_Bool _ecore_exe_data_generic_handler(void *data,
Ecore_Fd_Handler *fd_handler,
Ecore_Exe_Flags flags);
static Eina_Bool _ecore_exe_data_error_handler(void *data,
Ecore_Fd_Handler *fd_handler);
static Eina_Bool _ecore_exe_data_read_handler(void *data,
Ecore_Fd_Handler *fd_handler);
static Eina_Bool _ecore_exe_data_write_handler(void *data,
Ecore_Fd_Handler *fd_handler);
static void _ecore_exe_flush(Ecore_Exe *exe);
static void _ecore_exe_event_exe_data_free(void *data EINA_UNUSED,
void *ev);
static Ecore_Exe *_ecore_exe_is_it_alive(pid_t pid);
static Eina_Bool _ecore_exe_make_sure_its_dead(void *data);
static Eina_Bool _ecore_exe_make_sure_its_really_dead(void *data);
static Ecore_Exe_Event_Add *_ecore_exe_event_add_new(void);
static void _ecore_exe_event_add_free(void *data,
void *ev);
static void _ecore_exe_dead_attach(Ecore_Exe *exe);
EAPI int ECORE_EXE_EVENT_ADD = 0;
EAPI int ECORE_EXE_EVENT_DEL = 0;
EAPI int ECORE_EXE_EVENT_DATA = 0;
EAPI int ECORE_EXE_EVENT_ERROR = 0;
static Ecore_Exe *exes = NULL;
static const char *shell = NULL;
/* FIXME: This errno checking stuff should be put elsewhere for everybody to use.
* For now it lives here though, just to make testing easier.
*/
static int _ecore_exe_check_errno(int result,
const char *file,
int line);
2006-02-28 21:05:58 -08:00
#define E_IF_NO_ERRNO(result, foo, ok) \
while (((ok) = _ecore_exe_check_errno((result) = (foo), __FILE__, __LINE__)) == -1) sleep(1); \
if (ok)
#define E_NO_ERRNO(result, foo, ok) \
while (((ok) = _ecore_exe_check_errno((result) = (foo), __FILE__, __LINE__)) == -1) sleep(1)
#define E_IF_NO_ERRNO_NOLOOP(result, foo, ok) \
if (((ok) = _ecore_exe_check_errno((result) = (foo), __FILE__, __LINE__)))
static int
_ecore_exe_check_errno(int result,
const char *file EINA_UNUSED,
int line EINA_UNUSED)
{
int saved_errno = errno;
2006-02-28 21:05:58 -08:00
if (result == -1)
{
perror("*** errno reports ");
/* What is currently supported -
*
* pipe
* EFAULT Argument is not valid.
* EMFILE Too many file descriptors used by process.
* ENFILE Too many open files by system.
* read
* EAGAIN No data now, try again.
* EBADF This is not an fd that can be read.
* EFAULT This is not a valid buffer.
* EINTR Interupted by signal, try again.
* EINVAL This is not an fd that can be read.
* EIO I/O error.
* EISDIR This is a directory, and cannot be read.
* others Depending on what sort of thing we are reading from.
* close
* EBADF This is not an fd that can be closed.
* EINTR Interupted by signal, try again.
* EIO I/O error.
* dup2
* EBADF This is not an fd that can be dup2'ed.
* EBUSY Race condition between open() and dup()
* EINTR Interupted by signal, try again.
* EMFILE Too many file descriptors used by process.
* fcntl
* EACCES, EAGAIN Locked or mapped by something else, try again later.
* EBADF This is not an fd that can be fcntl'ed.
* EDEADLK This will cause a deadlock.
* EFAULT This is not a valid lock.
* EINTR Interupted by signal, try again.
* EINVAL This is not a valid arg.
* EMFILE Too many file descriptors used by process.
* ENOLCK Problem getting a lock.
* EPERM Not allowed to do that.
* fsync
* EBADF This is not an fd that is open for writing.
* EINVAL, EROFS This is not an fd that can be fsynced.
* EIO I/O error.
*
* How to use it -
* int ok = 0;
* int result;
*
* E_IF_NO_ERRNO(result, foo(bar), ok)
* {
* E_IF_NO_ERRNO_NOLOOP(result, foo(bar), ok)
* {
* }
* }
*
* if (!ok)
* {
* // Something failed, cleanup.
* }
*/
switch (saved_errno)
{
case EACCES:
case EAGAIN:
case EINTR:
{ /* Not now, try later. */
ERR("*** Must try again in %s @%u.", file, line);
result = -1;
break;
}
case EMFILE:
case ENFILE:
case ENOLCK:
{ /* Low on resources. */
ERR("*** Low on resources in %s @%u.", file,
line);
result = 0;
break;
}
case EIO:
{ /* I/O error. */
ERR("*** I/O error in %s @%u.", file, line);
result = 0;
break;
}
case EFAULT:
case EBADF:
case EINVAL:
case EROFS:
case EISDIR:
case EDEADLK:
case EPERM:
case EBUSY:
{ /* Programmer fucked up. */
ERR("*** NAUGHTY PROGRAMMER!!!\n"
"*** SPANK SPANK SPANK!!!\n"
"*** Now go fix your code in %s @%u. Tut tut tut!",
file, line);
result = 0;
break;
}
default:
{ /* Unsupported errno code, please add this one. */
ERR("*** NAUGHTY PROGRAMMER!!!\n"
"*** SPANK SPANK SPANK!!!\n"
"*** Unsupported errno code %d, please add this one.\n"
"*** Now go fix your code in %s @%u, from %s @%u. Tut tut tut!",
saved_errno, __FILE__, __LINE__, file, line);
result = 0;
break;
}
}
}
else /* Everything is fine. */
result = 1;
2006-02-28 21:05:58 -08:00
errno = saved_errno;
return result;
}
2010-10-17 00:03:28 -07:00
/**
* @addtogroup Ecore_Exe_Group
*
2010-10-17 00:03:28 -07:00
* @{
*/
static int run_pri = ECORE_EXE_PRIORITY_INHERIT;
/**
* Sets the priority at which to launch processes
*
* This sets the priority of processes run by ecore_exe_run() and
* ecore_exe_pipe_run().
* @li On Windows, the child process is created by default with the
* @ref ECORE_EXE_WIN32_PRIORITY_NORMAL priority, unless the calling
* process is in @ref ECORE_EXE_WIN32_PRIORITY_IDLE or
* @ref ECORE_EXE_WIN32_PRIORITY_BELOW_NORMAL priority. In that case, the
* child process inherits this priority.
* @li On other platforms, if set to @ref ECORE_EXE_PRIORITY_INHERIT child
* processes inherits the priority of their parent. This is the default.
*
* @param pri value a Ecore_Exe_Win32_Priority value on Windows, -20
* to 19 or @ref ECORE_EXE_PRIORITY_INHERIT on other OS.
*/
EAPI void
ecore_exe_run_priority_set(int pri)
{
EINA_MAIN_LOOP_CHECK_RETURN;
run_pri = pri;
}
/**
* Gets the priority at which to launch processes
*
* This gets ths priority of launched processes. See
* ecore_exe_run_priority_set() for details. This just returns the value set
* by this call.
*
* @return the value set by ecore_exe_run_priority_set()
*/
EAPI int
ecore_exe_run_priority_get(void)
{
EINA_MAIN_LOOP_CHECK_RETURN_VAL(0);
return run_pri;
}
/**
* Spawns a child process.
*
* This is now just a thin wrapper around ecore_exe_pipe_run()
* @note When you use this function you will have no permissions
* to write or read on the pipe that connects you with the spwaned process.
* If you need to do that use ecore_exe_pipe_run() with the
* appropriated flags.
*
* @param exe_cmd The command to run with @c /bin/sh.
* @param data Data to attach to the returned process handle.
* @return A process handle to the spawned process.
*/
EAPI Ecore_Exe *
ecore_exe_run(const char *exe_cmd,
const void *data)
{
EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
return ecore_exe_pipe_run(exe_cmd, 0, data);
}
/**
* Spawns a child process with its stdin/out available for communication.
*
* This function forks and runs the given command using @c /bin/sh.
*
* Note that the process handle is only valid until a child process
* terminated event is received. After all handlers for the child process
* terminated event have been called, the handle will be freed by Ecore.
*
* This function does the same thing as ecore_exe_run(), but also makes the
e: 1. configure/build changes to allow cross-compiling painlessly 2. pager module namespace changes - this was still dirty afdter the namespace cleanup, so clean it up 3. add a powersave subsystem - doesnt have an "automatic" way to turn on and off right now, this i think is best provided by modules (that do things like monitor acpi status's (eg close lid of laptop), AC power status etc. etc. this allows e to nicely defer "power" expensive actions to avoid disk spinups etc. 4. move to use the new ecore poller system - discussed long ago as part of power management/saving issues. now it exists 5. add a canvas idle flush call that helsp cope with the new shm greedy software x11 engine stuff 6. use the new powersave subsystem where appropriate 7. fix non-zeroed/initted memory access in e_fm_main 8. fix mem leak for e menus 9. remove ipc handlers for changed/removed config values 10. use animaotr not timer for menu scrolls - then menu scrolls obey the fps config 11. fix up timer/poll happienss of cursor idle stuff 12. remove avoid damage from popups for now - causing problems 13. change battery and temp readouts to b e shorter so they fit 14. pager can emit signals on focus change for mini-windows now 15. temperature module now uses a slave process and uses stdin/out to talk to it and get output - this makes e smoother as in my expereicne i found getting the temp on my laptop actually took like 200ms so e "hang" for 200ms while reading the acpi files - so now the subprocess does it and just writesa back to e when it gets it. ecore: 1. add ecore_pollers. see the documentation on them in doxygen comments :) 2. fix timers to only go off when they have to - bug there that made e's select time out a LOT more than it needed to. defensive coding hid the problem. now fixed. e should be much more power friendly now. 3. formatting/niceness in ecore_exe stuff 4. some comments on comments with SIGIO ideas vs. select 5. add call to be able to add an idle enterer at the start of the list of them, not just the end (as has been the default) 6. fix ecore_evas to support auto evas idler calls after 0.5 secs of idle in all canvases - and to do it right 7. if argb destination - set the shape EVENT shape (to mask out events in transparent regions much like shape does withotu translucency) 8. in ecore_x add support for the event shape evas: 1. fix cache to work properly and not just always fill up (as it seemed to like to think cahce useage dropped below 0 when it didnt and thus just over-fill) 2. software x11 engine now ONLY uses shm segments - no ximages over the socket. this ximage hack was there to avoid the 2 round trips involved in setting up an shm image - now i mitigated that wih an shm image cache pool. it keeps shm images around and repurposes them for new update regions if appropriate. this means many fewer shm creates (about 1/100th the number) and since we recycle the memory less 0 memory page filling by the kernel - in the end, i recorded about a 10-20% speedup over the old software x11 engine. simple tests i have seen up to 120% speedups. idle flush now does something - it frees all the cached shm segments. it has a hard-coded limit of 4mb worth of shm segments (or 32 segments - whichever comes first) to keep around. once can never complain much about speedups methinks :). also evas will defer sync until the NEXT frame is written - this means evas can calculate the next frame of data while x dma's/copies the images to the screen at the same time (if you hve a dual core or multi-cpu machnike or your xserver is able to use DMA to copy image data to the screen/video ram then this should see a decent speedup). SVN revision: 33448
2008-01-10 23:33:57 -08:00
* standard in and/or out as well as stderr from the child process available
* for reading or writing. To write use ecore_exe_send(). To read listen to
* ECORE_EXE_EVENT_DATA or ECORE_EXE_EVENT_ERROR events (set up handlers).
* Ecore may buffer read and error data until a newline character if asked
* for with the @p flags. All data will be included in the events (newlines
* will be replaced with NULLS if line buffered). ECORE_EXE_EVENT_DATA events
* will only happen if the process is run with ECORE_EXE_PIPE_READ enabled
* in the flags. The same with the error version. Writing will only be
* allowed with ECORE_EXE_PIPE_WRITE enabled in the flags.
*
* @param exe_cmd The command to run with @c /bin/sh.
* @param flags The flag parameters for how to deal with inter-process I/O
* @param data Data to attach to the returned process handle.
* @return A process handle to the spawned process.
*/
EAPI Ecore_Exe *
ecore_exe_pipe_run(const char *exe_cmd,
Ecore_Exe_Flags flags,
const void *data)
{
Ecore_Exe *exe = NULL;
int statusPipe[2] = { -1, -1 };
int errorPipe[2] = { -1, -1 };
int readPipe[2] = { -1, -1 };
int writePipe[2] = { -1, -1 };
int n = 0;
int ok = 1;
int result;
2006-02-28 21:05:58 -08:00
EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
e: 1. configure/build changes to allow cross-compiling painlessly 2. pager module namespace changes - this was still dirty afdter the namespace cleanup, so clean it up 3. add a powersave subsystem - doesnt have an "automatic" way to turn on and off right now, this i think is best provided by modules (that do things like monitor acpi status's (eg close lid of laptop), AC power status etc. etc. this allows e to nicely defer "power" expensive actions to avoid disk spinups etc. 4. move to use the new ecore poller system - discussed long ago as part of power management/saving issues. now it exists 5. add a canvas idle flush call that helsp cope with the new shm greedy software x11 engine stuff 6. use the new powersave subsystem where appropriate 7. fix non-zeroed/initted memory access in e_fm_main 8. fix mem leak for e menus 9. remove ipc handlers for changed/removed config values 10. use animaotr not timer for menu scrolls - then menu scrolls obey the fps config 11. fix up timer/poll happienss of cursor idle stuff 12. remove avoid damage from popups for now - causing problems 13. change battery and temp readouts to b e shorter so they fit 14. pager can emit signals on focus change for mini-windows now 15. temperature module now uses a slave process and uses stdin/out to talk to it and get output - this makes e smoother as in my expereicne i found getting the temp on my laptop actually took like 200ms so e "hang" for 200ms while reading the acpi files - so now the subprocess does it and just writesa back to e when it gets it. ecore: 1. add ecore_pollers. see the documentation on them in doxygen comments :) 2. fix timers to only go off when they have to - bug there that made e's select time out a LOT more than it needed to. defensive coding hid the problem. now fixed. e should be much more power friendly now. 3. formatting/niceness in ecore_exe stuff 4. some comments on comments with SIGIO ideas vs. select 5. add call to be able to add an idle enterer at the start of the list of them, not just the end (as has been the default) 6. fix ecore_evas to support auto evas idler calls after 0.5 secs of idle in all canvases - and to do it right 7. if argb destination - set the shape EVENT shape (to mask out events in transparent regions much like shape does withotu translucency) 8. in ecore_x add support for the event shape evas: 1. fix cache to work properly and not just always fill up (as it seemed to like to think cahce useage dropped below 0 when it didnt and thus just over-fill) 2. software x11 engine now ONLY uses shm segments - no ximages over the socket. this ximage hack was there to avoid the 2 round trips involved in setting up an shm image - now i mitigated that wih an shm image cache pool. it keeps shm images around and repurposes them for new update regions if appropriate. this means many fewer shm creates (about 1/100th the number) and since we recycle the memory less 0 memory page filling by the kernel - in the end, i recorded about a 10-20% speedup over the old software x11 engine. simple tests i have seen up to 120% speedups. idle flush now does something - it frees all the cached shm segments. it has a hard-coded limit of 4mb worth of shm segments (or 32 segments - whichever comes first) to keep around. once can never complain much about speedups methinks :). also evas will defer sync until the NEXT frame is written - this means evas can calculate the next frame of data while x dma's/copies the images to the screen at the same time (if you hve a dual core or multi-cpu machnike or your xserver is able to use DMA to copy image data to the screen/video ram then this should see a decent speedup). SVN revision: 33448
2008-01-10 23:33:57 -08:00
if (!exe_cmd) return NULL;
exe = calloc(1, sizeof(Ecore_Exe));
if (!exe) return NULL;
2006-02-28 21:05:58 -08:00
if ((flags & ECORE_EXE_PIPE_AUTO) && (!(flags & ECORE_EXE_PIPE_ERROR))
&& (!(flags & ECORE_EXE_PIPE_READ)))
e: 1. configure/build changes to allow cross-compiling painlessly 2. pager module namespace changes - this was still dirty afdter the namespace cleanup, so clean it up 3. add a powersave subsystem - doesnt have an "automatic" way to turn on and off right now, this i think is best provided by modules (that do things like monitor acpi status's (eg close lid of laptop), AC power status etc. etc. this allows e to nicely defer "power" expensive actions to avoid disk spinups etc. 4. move to use the new ecore poller system - discussed long ago as part of power management/saving issues. now it exists 5. add a canvas idle flush call that helsp cope with the new shm greedy software x11 engine stuff 6. use the new powersave subsystem where appropriate 7. fix non-zeroed/initted memory access in e_fm_main 8. fix mem leak for e menus 9. remove ipc handlers for changed/removed config values 10. use animaotr not timer for menu scrolls - then menu scrolls obey the fps config 11. fix up timer/poll happienss of cursor idle stuff 12. remove avoid damage from popups for now - causing problems 13. change battery and temp readouts to b e shorter so they fit 14. pager can emit signals on focus change for mini-windows now 15. temperature module now uses a slave process and uses stdin/out to talk to it and get output - this makes e smoother as in my expereicne i found getting the temp on my laptop actually took like 200ms so e "hang" for 200ms while reading the acpi files - so now the subprocess does it and just writesa back to e when it gets it. ecore: 1. add ecore_pollers. see the documentation on them in doxygen comments :) 2. fix timers to only go off when they have to - bug there that made e's select time out a LOT more than it needed to. defensive coding hid the problem. now fixed. e should be much more power friendly now. 3. formatting/niceness in ecore_exe stuff 4. some comments on comments with SIGIO ideas vs. select 5. add call to be able to add an idle enterer at the start of the list of them, not just the end (as has been the default) 6. fix ecore_evas to support auto evas idler calls after 0.5 secs of idle in all canvases - and to do it right 7. if argb destination - set the shape EVENT shape (to mask out events in transparent regions much like shape does withotu translucency) 8. in ecore_x add support for the event shape evas: 1. fix cache to work properly and not just always fill up (as it seemed to like to think cahce useage dropped below 0 when it didnt and thus just over-fill) 2. software x11 engine now ONLY uses shm segments - no ximages over the socket. this ximage hack was there to avoid the 2 round trips involved in setting up an shm image - now i mitigated that wih an shm image cache pool. it keeps shm images around and repurposes them for new update regions if appropriate. this means many fewer shm creates (about 1/100th the number) and since we recycle the memory less 0 memory page filling by the kernel - in the end, i recorded about a 10-20% speedup over the old software x11 engine. simple tests i have seen up to 120% speedups. idle flush now does something - it frees all the cached shm segments. it has a hard-coded limit of 4mb worth of shm segments (or 32 segments - whichever comes first) to keep around. once can never complain much about speedups methinks :). also evas will defer sync until the NEXT frame is written - this means evas can calculate the next frame of data while x dma's/copies the images to the screen at the same time (if you hve a dual core or multi-cpu machnike or your xserver is able to use DMA to copy image data to the screen/video ram then this should see a decent speedup). SVN revision: 33448
2008-01-10 23:33:57 -08:00
/* We need something to auto pipe. */
flags |= ECORE_EXE_PIPE_READ | ECORE_EXE_PIPE_ERROR;
exe->child_fd_error = -1;
exe->child_fd_read = -1;
exe->child_fd_write = -1;
2006-02-14 20:55:14 -08:00
exe->child_fd_error_x = -1;
exe->child_fd_read_x = -1;
exe->child_fd_write_x = -1;
/* Create some pipes. */
2006-02-28 21:05:58 -08:00
if (ok)
{
E_IF_NO_ERRNO_NOLOOP(result, pipe(statusPipe), ok)
{
}
}
if (ok && (flags & ECORE_EXE_PIPE_ERROR))
{
E_IF_NO_ERRNO_NOLOOP(result, pipe(errorPipe), ok)
{
exe->child_fd_error = errorPipe[0];
exe->child_fd_error_x = errorPipe[1];
}
}
if (ok && (flags & ECORE_EXE_PIPE_READ))
{
E_IF_NO_ERRNO_NOLOOP(result, pipe(readPipe), ok)
{
exe->child_fd_read = readPipe[0];
exe->child_fd_read_x = readPipe[1];
}
}
if (ok && (flags & ECORE_EXE_PIPE_WRITE))
{
E_IF_NO_ERRNO_NOLOOP(result, pipe(writePipe), ok)
{
exe->child_fd_write = writePipe[1];
exe->child_fd_write_x = writePipe[0];
}
}
if (ok)
{
pid_t pid = 0;
volatile int vfork_exec_errno = 0;
/* FIXME: I should double check this. After a quick look around, this is already done, but via a more modern method. */
/* signal(SIGPIPE, SIG_IGN); We only want EPIPE on errors */
pid = fork();
if (pid == -1)
{
ERR("Failed to fork process");
pid = 0;
}
else if (pid == 0) /* child */
{
if (run_pri != ECORE_EXE_PRIORITY_INHERIT)
{
#ifdef PRIO_PROCESS
if ((run_pri >= -20) && (run_pri <= 19))
setpriority(PRIO_PROCESS, 0, run_pri);
#else
#warning "Your OS/libc does not provide PRIO_PROCESS (and possibly setpriority())"
#warning "This is a POSIX-1.2001 standard and it is highly encouraged that you"
#warning "Have support for this"
#endif
}
/* dup2 STDERR, STDIN, and STDOUT. dup2() allegedly closes the
* second pipe if it's open. On the other hand, there was the
* Great FD Leak Scare of '06, so let's be paranoid. */
if (ok && (flags & ECORE_EXE_PIPE_ERROR))
{
E_NO_ERRNO(result, close(STDERR_FILENO), ok);
E_NO_ERRNO(result, dup2(errorPipe[1], STDERR_FILENO), ok);
}
if (ok && (flags & ECORE_EXE_PIPE_READ))
{
E_NO_ERRNO(result, close(STDOUT_FILENO), ok);
E_NO_ERRNO(result, dup2(readPipe[1], STDOUT_FILENO), ok);
}
if (ok && (flags & ECORE_EXE_PIPE_WRITE))
{
E_NO_ERRNO(result, close(STDIN_FILENO), ok);
E_NO_ERRNO(result, dup2(writePipe[0], STDIN_FILENO), ok);
}
if (ok)
{
/* Setup the status pipe. */
2010-09-29 23:09:20 -07:00
E_NO_ERRNO(result, close(statusPipe[0]), ok);
E_IF_NO_ERRNO(result, fcntl(statusPipe[1], F_SETFD, FD_CLOEXEC), ok) /* close on exec shows success */
{
/* Run the actual command. */
_ecore_exe_exec_it(exe_cmd, flags); /* no return */
}
}
/* Something went 'orribly wrong. */
vfork_exec_errno = errno;
/* Close the pipes. */
if (flags & ECORE_EXE_PIPE_ERROR)
E_NO_ERRNO(result, close(errorPipe[1]), ok);
if (flags & ECORE_EXE_PIPE_READ)
E_NO_ERRNO(result, close(readPipe[1]), ok);
if (flags & ECORE_EXE_PIPE_WRITE)
E_NO_ERRNO(result, close(writePipe[0]), ok);
E_NO_ERRNO(result, close(statusPipe[1]), ok);
_exit(-1);
}
else /* parent */
{
/* Close the unused pipes. */
E_NO_ERRNO(result, close(statusPipe[1]), ok);
/* FIXME: after having a good look at the current e fd
* handling, investigate fcntl(dataPipe[x], F_SETSIG, ...) */
/* FIXME: above F_SETSIG etc. - this is async SIGIO based IO
* which is also linux specific so we probably don't want to
* do this as long as select() is working fine. the only time
* we really want to think of SIGIO async IO is when it all
* actually works basically everywhere and we can turn all
* IO into DMA async activities (i.e. you do a read() then
* the read is complete not on return but when you get a
* SIGIO - the read() just starts the transfer and it is
* completed in the background by DMA (or whatever mechanism
* the kernel choses)) */
/* Wait for it to start executing. */
/* FIXME: this doesn't seem very nice - we sit and block
* waiting on a child process... even though it's just
* the segment between the fork() and the exec) it just feels
* wrong */
for (;; )
{
char buf;
E_NO_ERRNO(result, read(statusPipe[0], &buf, 1), ok);
if (result == 0)
{
if (vfork_exec_errno != 0)
{
n = vfork_exec_errno;
ERR("Could not start \"%s\"", exe_cmd);
pid = 0;
}
break;
}
2010-09-29 23:09:20 -07:00
}
/* Close the status pipe. */
E_NO_ERRNO(result, close(statusPipe[0]), ok);
}
if (pid)
{
/* Setup the exe structure. */
ECORE_MAGIC_SET(exe, ECORE_MAGIC_EXE);
exe->start_bytes = -1;
exe->end_bytes = -1;
exe->start_lines = -1;
exe->end_lines = -1;
exe->pid = pid;
exe->flags = flags;
exe->data = (void *)data;
if ((exe->cmd = strdup(exe_cmd)))
2010-09-29 23:09:20 -07:00
{
if (flags & ECORE_EXE_PIPE_ERROR) /* Setup the error stuff. */
{
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_error, F_SETFL,
O_NONBLOCK), ok) {
}
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_error, F_SETFD,
FD_CLOEXEC), ok) {
}
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_error_x, F_SETFD,
FD_CLOEXEC), ok) {
}
{
exe->error_fd_handler =
ecore_main_fd_handler_add(exe->child_fd_error,
ECORE_FD_READ,
_ecore_exe_data_error_handler,
exe, NULL, NULL);
if (!exe->error_fd_handler)
ok = 0;
}
}
if (ok && (flags & ECORE_EXE_PIPE_READ)) /* Setup the read stuff. */
{
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_read, F_SETFL,
O_NONBLOCK), ok) {
}
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_read, F_SETFD,
FD_CLOEXEC), ok) {
}
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_read_x, F_SETFD,
FD_CLOEXEC), ok) {
}
{
exe->read_fd_handler =
ecore_main_fd_handler_add(exe->child_fd_read,
ECORE_FD_READ,
_ecore_exe_data_read_handler,
exe, NULL, NULL);
if (!exe->read_fd_handler)
ok = 0;
}
}
if (ok && (flags & ECORE_EXE_PIPE_WRITE)) /* Setup the write stuff. */
{
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_write, F_SETFL,
O_NONBLOCK), ok) {
}
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_write, F_SETFD,
FD_CLOEXEC), ok) {
}
E_IF_NO_ERRNO(result,
fcntl(exe->child_fd_write_x, F_SETFD,
FD_CLOEXEC), ok) {
}
{
exe->write_fd_handler =
ecore_main_fd_handler_add(exe->child_fd_write,
ECORE_FD_WRITE,
_ecore_exe_data_write_handler,
exe, NULL, NULL);
if (exe->write_fd_handler)
ecore_main_fd_handler_active_set(exe->write_fd_handler, 0); /* Nothing to write to start with. */
else
ok = 0;
}
}
exes = (Ecore_Exe *)eina_inlist_append(EINA_INLIST_GET(exes), EINA_INLIST_GET(exe));
n = 0;
2010-09-29 23:09:20 -07:00
}
else
ok = 0;
}
else
ok = 0;
}
if (!ok) /* Something went wrong, so pull down everything. */
{
if (exe->pid) ecore_exe_terminate(exe);
IF_FN_DEL(ecore_exe_free, exe);
}
2005-12-30 11:28:54 -08:00
else
{
Ecore_Exe_Event_Add *e;
2010-09-29 23:09:20 -07:00
e = _ecore_exe_event_add_new();
if (e)
{
e->exe = exe;
if (e) /* Send the event. */
ecore_event_add(ECORE_EXE_EVENT_ADD, e,
_ecore_exe_event_add_free, NULL);
}
/* INF("Running as %d for %s.\n", exe->pid, exe->cmd); */
}
errno = n;
return exe;
}
/**
* Defines a function to be called before really freeing the handle data.
*
* This might be useful for language bindings such as Python and Perl
* that need to deallocate wrappers associated with this handle.
*
* This handle should never be modified by this call. It should be
* considered informative only. All getters are valid when the given
* function is called back.
*
* @param exe The child process to attach the pre_free function.
* @param func The function to call before @a exe is freed.
*/
EAPI void
ecore_exe_callback_pre_free_set(Ecore_Exe *exe,
Ecore_Exe_Cb func)
{
EINA_MAIN_LOOP_CHECK_RETURN;
if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
{
ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE,
"ecore_exe_callback_pre_free_set");
return;
}
exe->pre_free_cb = func;
}
/**
* Sends data to the given child process which it receives on stdin.
*
* This function writes to a child processes standard in, with unlimited
* buffering. This call will never block. It may fail if the system runs out
* of memory.
*
2006-01-04 12:33:58 -08:00
* @param exe The child process to send to
* @param data The data to send
* @param size The size of the data to send, in bytes
* @return @c EINA_TRUE if successful, @c EINA_FALSE on failure.
*/
EAPI Eina_Bool
ecore_exe_send(Ecore_Exe *exe,
const void *data,
int size)
{
void *buf;
EINA_MAIN_LOOP_CHECK_RETURN_VAL(EINA_FALSE);
if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
{
ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_send");
return EINA_FALSE;
}
if (exe->close_stdin)
{
ERR("Ecore_Exe %p stdin is closed! Cannot send %d bytes from %p",
exe, size, data);
return EINA_FALSE;
}
if (exe->child_fd_write == -1)
{
ERR("Ecore_Exe %p created without ECORE_EXE_PIPE_WRITE! "
"Cannot send %d bytes from %p", exe, size, data);
return EINA_FALSE;
}
buf = realloc(exe->write_data_buf, exe->write_data_size + size);
if (!buf) return EINA_FALSE;
exe->write_data_buf = buf;
memcpy((char *)exe->write_data_buf + exe->write_data_size, data, size);
exe->write_data_size += size;
if (exe->write_fd_handler)
ecore_main_fd_handler_active_set(exe->write_fd_handler, ECORE_FD_WRITE);
2006-02-28 21:05:58 -08:00
return EINA_TRUE;
}
/**
* The stdin of the given child process will close when the write buffer is empty.
*
* @param exe The child process
*/
EAPI void
ecore_exe_close_stdin(Ecore_Exe *exe)
{
EINA_MAIN_LOOP_CHECK_RETURN;
if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
{
ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_close_stdin");
return;
}
exe->close_stdin = 1;
}
/**
* Sets the auto pipe limits for the given process handle. On Windows
* this function does nothing.
*
* @param exe The given process handle.
* @param start_bytes limit of bytes at start of output to buffer.
* @param end_bytes limit of bytes at end of output to buffer.
* @param start_lines limit of lines at start of output to buffer.
* @param end_lines limit of lines at end of output to buffer.
*/
EAPI void
ecore_exe_auto_limits_set(Ecore_Exe *exe,
int start_bytes,
int end_bytes,
int start_lines,
int end_lines)
{
EINA_MAIN_LOOP_CHECK_RETURN;
if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
{
ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_auto_limits_set");
return;
}
/* FIXME: sanitize the input. */
exe->start_bytes = start_bytes;
2006-02-28 21:05:58 -08:00
exe->end_bytes = end_bytes;
exe->start_lines = start_lines;
2006-02-28 21:05:58 -08:00
exe->end_lines = end_lines;
/* FIXME: get this can of worms working.
*
* capture stderr & stdout internally
*
* raster and onefang keep moving the goal posts on this one. It started out as
* "show users the error output if an exe fails" and is rapidly approaching
* "alternative method of getting the data, poll vs event driven". Some serious
* thinking needs to be applied to this. Do we really want to go that far? If
* so, we should change the names. The basic design will probably remain the
* same which ever way we go. The constant goal post moving is probably due to
* generic design methods leading to feature creep as we inspired each other to
* more generic designs. It does seem like the closer we get to poll driven,
* the more issues and corner cases there are.
*
* Instead of doing the usual register an event handler thing, we are ecore_exe,
* we can take some short cuts. Don't send the events, just leave the exe buffers
* as is until the user asks for them, then return the event.
*
* start = 0, end = 0; clogged arteries get flushed, everything is ignored.
* start = -1, end = -1; clogged arteries get transferred to internal buffers. Actually, either == -1 means buffer everything.
* start = X, end = 0; buffer first X out of clogged arteries, flush and ignore rest.
* start = 0, end = X; circular buffer X
* start = X, end = Y; buffer first X out of clogged arteries, circular buffer Y from beginning.
*
* bytes vs lines, which ever one reaches the limit first.
* Before we go beyond the start+end limit, leave the end buffer empty, and store both in the start buffer, coz they overlap.
* After we pass the the start+end limit, insert "\n...\n" at the end of the start buffer, copy the rest to the end buffer, then store in the end buffer.
*
* Other issues -
* Spank programmer for polling data if polling is not turned on.
* Spank programmer for setting up event callbacks if polling is turned on.
* Spank programmer for freeing the event data if it came from the event system, as that autofrees.
* Spank the programmer if they try to set the limits bigger than what has been gathered & ignored already, coz they just lost data.
* Spank onefang and raster for opening this can of worms.
* Should we have separate out/err limits?
* Should we remove from the internal buffer the data that was delivered already?
* If so, what to do about limits, start, and end? They could loose their meaning.
*/
}
/**
* Gets the auto pipe data for the given process hand