svn update: 48958 (latest:48959)
[framework/uifw/ecore.git] / src / lib / ecore / ecore_exe.c
1 /*
2  * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2
3  */
4
5 #ifdef HAVE_CONFIG_H
6 # include <config.h>
7 #endif
8
9 #if defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__NetBSD__)
10 # include <sys/time.h>
11 # include <sys/resource.h>
12 #endif
13
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <unistd.h>
20 #include <fcntl.h>
21
22 #ifdef HAVE_SYS_WAIT_H
23 # include <sys/wait.h>
24 #endif
25
26 #include "Ecore.h"
27 #include "ecore_private.h"
28
29
30    /* FIXME: Getting respawn to work
31     *
32     * There is no way that we can do anything about the internal state info of
33     * an external exe.  The same can be said about the state of user code.  User
34     * code in this context means the code that is using ecore_exe to manage exe's
35     * for it.
36     *
37     * Document that the exe must be respawnable, in other words, there is no
38     * state that it cannot regenerate by just killing it and starting it again.
39     * This includes state that the user code knows about, as the respawn is
40     * transparent to that code.  On the other hand, maybe a respawn event might
41     * be useful, or maybe resend the currently non existant add event.  For
42     * consistancy with ecore_con, an add event is good anyway.
43     *
44     * The Ecore_exe structure is reused for respawning, so that the (opaque)
45     * pointer held by the user remains valid.  This means that the Ecore_Exe
46     * init and del functions may need to be split into two parts each to avoid
47     * duplicating code - common code part, and the rest.  This implies that
48     * the unchanging members mentioned next should NEVER change.
49     *
50     * These structure members don't need to change -
51     *   __list_data       - we stay on the list
52     *   ECORE_MAGIC       - this is a constant
53     *   data              - passed in originally
54     *   cmd               - passed in originally
55     *   flags             - passed in originally
56     *
57     * These structure members need to change -
58     *   tag               - state that must be regenerated, zap it
59     *   pid               - it will be different
60     *   child_fd_write    - it will be different
61     *   child_fd_read     - it will be different
62     *   child_fd_error    - it will be different
63     *   write_fd_handler  - we cannot change the fd used by a handler, this changes coz the fd changes.
64     *   read_fd_handler   - we cannot change the fd used by a handler, this changes coz the fd changes.
65     *   error_fd_handler  - we cannot change the fd used by a handler, this changes coz the fd changes.
66     *
67     * Hmm, the read, write, and error buffers could be tricky.
68     * They are not atomic, and could be in a semi complete state.
69     * They fall into the "state must be regenerated" mentioned above.
70     * A respawn/add event should take care of it.
71     *
72     * These structure members need to change -
73     *   write_data_buf    - state that must be regenerated, zap it
74     *   write_data_size   - state that must be regenerated, zap it
75     *   write_data_offset - state that must be regenerated, zap it
76     *   read_data_buf     - state that must be regenerated, zap it
77     *   read_data_size    - state that must be regenerated, zap it
78     *   error_data_buf    - state that must be regenerated, zap it
79     *   error_data_size   - state that must be regenerated, zap it
80     *   close_write       - state that must be regenerated, zap it
81     *
82     * There is the problem that an exe that fell over and needs respawning
83     * might keep falling over, keep needing to be respawned, and tie up system
84     * resources with the constant respawning.  An exponentially increasing
85     * timeout (with maximum timeout) between respawns should take care of that.
86     * Although this is not a "contention for a resource" problem, the exe falling
87     * over may be, so a random element added to the timeout may help, and won't
88     * hurt.  The user code may need to be informed that a timeout is in progress.
89     */
90
91 struct _Ecore_Exe
92 {
93    EINA_INLIST;
94    ECORE_MAGIC;
95    pid_t pid;
96    void *data;
97    char *tag, *cmd;
98    Ecore_Exe_Flags  flags;
99    Ecore_Fd_Handler *write_fd_handler; /* the fd_handler to handle write to child - if this was used, or NULL if not */
100    Ecore_Fd_Handler *read_fd_handler; /* the fd_handler to handle read from child - if this was used, or NULL if not */
101    Ecore_Fd_Handler *error_fd_handler; /* the fd_handler to handle errors from child - if this was used, or NULL if not */
102    void  *write_data_buf; /* a data buffer for data to write to the child -
103                                  * realloced as needed for more data and flushed when the fd handler says writes are possible
104                                  */
105    int write_data_size; /* the size in bytes of the data buffer */
106    int write_data_offset; /* the offset in bytes in the data buffer */
107    void *read_data_buf; /* data read from the child awating delivery to an event */
108    int read_data_size; /* data read from child in bytes */
109    void *error_data_buf; /* errors read from the child awating delivery to an event */
110    int error_data_size; /* errors read from child in bytes */
111    int child_fd_write;  /* fd to write TO to send data to the child */
112    int child_fd_read;   /* fd to read FROM when child has sent us (the parent) data */
113    int child_fd_error;  /* fd to read FROM when child has sent us (the parent) errors */
114    int child_fd_write_x;        /* fd to write TO to send data to the child */
115    int child_fd_read_x; /* fd to read FROM when child has sent us (the parent) data */
116    int child_fd_error_x;        /* fd to read FROM when child has sent us (the parent) errors */
117    Eina_Bool close_stdin : 1;
118
119    int start_bytes, end_bytes, start_lines, end_lines; /* Number of bytes/lines to auto pipe at start/end of stdout/stderr. */
120
121    Ecore_Timer *doomsday_clock; /* The Timer of Death.  Muahahahaha. */
122    void *doomsday_clock_dead; /* data for the doomsday clock */
123
124    void (*pre_free_cb)(void *data, const Ecore_Exe *exe);
125 };
126
127
128 /* TODO: Something to let people build a command line and does auto escaping -
129  *
130  * ecore_exe_snprintf()
131  *
132  *   OR
133  *
134  * cmd = ecore_exe_comand_parameter_append(cmd, "firefox");
135  * cmd = ecore_exe_comand_parameter_append(cmd, "http://www.foo.com/bar.html?baz=yes");
136  * each parameter appended is one argument, and it gets escaped, quoted, and
137  * appended with a preceeding space.  The first is the command off course.
138  */
139
140 struct _ecore_exe_dead_exe
141 {
142    pid_t pid;
143    char *cmd;
144 };
145
146 static inline void _ecore_exe_exec_it(const char *exe_cmd, Ecore_Exe_Flags flags);
147 static int _ecore_exe_data_generic_handler(void *data, Ecore_Fd_Handler *fd_handler, Ecore_Exe_Flags flags);
148 static int _ecore_exe_data_error_handler(void *data, Ecore_Fd_Handler *fd_handler);
149 static int _ecore_exe_data_read_handler(void *data, Ecore_Fd_Handler *fd_handler);
150 static int _ecore_exe_data_write_handler(void *data, Ecore_Fd_Handler *fd_handler);
151 static void _ecore_exe_flush(Ecore_Exe * exe);
152 static void _ecore_exe_event_exe_data_free(void *data __UNUSED__, void *ev);
153 static Ecore_Exe *_ecore_exe_is_it_alive(pid_t pid);
154 static int _ecore_exe_make_sure_its_dead(void *data);
155 static int _ecore_exe_make_sure_its_really_dead(void *data);
156 static Ecore_Exe_Event_Add *_ecore_exe_event_add_new(void);
157 static void _ecore_exe_event_add_free(void *data, void *ev);
158 static void _ecore_exe_dead_attach(Ecore_Exe *exe);
159
160 EAPI int ECORE_EXE_EVENT_ADD = 0;
161 EAPI int ECORE_EXE_EVENT_DEL = 0;
162 EAPI int ECORE_EXE_EVENT_DATA = 0;
163 EAPI int ECORE_EXE_EVENT_ERROR = 0;
164
165 static Ecore_Exe *exes = NULL;
166 static const char *shell = NULL;
167
168 /* FIXME: This errno checking stuff should be put elsewhere for everybody to use.
169  * For now it lives here though, just to make testing easier.
170  */
171 static int _ecore_exe_check_errno(int result, const char *file, int line);
172
173 #define E_IF_NO_ERRNO(result, foo, ok) \
174   while (((ok) = _ecore_exe_check_errno( (result) = (foo), __FILE__, __LINE__)) == -1)   sleep(1); \
175   if (ok)
176
177 #define E_NO_ERRNO(result, foo, ok) \
178   while (((ok) = _ecore_exe_check_errno( (result) = (foo), __FILE__, __LINE__)) == -1)   sleep(1)
179
180 #define E_IF_NO_ERRNO_NOLOOP(result, foo, ok) \
181   if (((ok) = _ecore_exe_check_errno( (result) = (foo), __FILE__, __LINE__)))
182
183 static int
184 _ecore_exe_check_errno(int result, const char *file, int line)
185 {
186    int saved_errno = errno;
187
188    if (result == -1)
189      {
190         perror("*** errno reports ");
191 /* What is currently supported -
192  *
193  *   pipe
194  *     EFAULT  Argument is not valid.
195  *     EMFILE  Too many file descriptors used by process.
196  *     ENFILE  Too many open files by system.
197  *   read
198  *     EAGAIN  No data now, try again.
199  *     EBADF   This is not an fd that can be read.
200  *     EFAULT  This is not a valid buffer.
201  *     EINTR   Interupted by signal, try again.
202  *     EINVAL  This is not an fd that can be read.
203  *     EIO     I/O error.
204  *     EISDIR  This is a directory, and cannot be read.
205  *     others  Depending on what sort of thing we are reading from.
206  *   close
207  *     EBADF   This is not an fd that can be closed.
208  *     EINTR   Interupted by signal, try again.
209  *     EIO     I/O error.
210  *   dup2
211  *     EBADF   This is not an fd that can be dup2'ed.
212  *     EBUSY   Race condition between open() and dup()
213  *     EINTR   Interupted by signal, try again.
214  *     EMFILE  Too many file descriptors used by process.
215  *   fcntl
216  *     EACCES, EAGAIN  Locked or mapped by something else, try again later.
217  *     EBADF   This is not an fd that can be fcntl'ed.
218  *     EDEADLK This will cause a deadlock.
219  *     EFAULT  This is not a valid lock.
220  *     EINTR   Interupted by signal, try again.
221  *     EINVAL  This is not a valid arg.
222  *     EMFILE  Too many file descriptors used by process.
223  *     ENOLCK  Problem getting a lock.
224  *     EPERM   Not allowed to do that.
225  *   fsync
226  *     EBADF   This is not an fd that is open for writing.
227  *     EINVAL, EROFS  This is not an fd that can be fsynced.
228  *     EIO     I/O error.
229  *
230  * How to use it -
231  *    int ok = 0;
232  *    int result;
233  *
234  *    E_IF_NO_ERRNO(result, foo(bar), ok)
235  *      {
236  *         E_IF_NO_ERRNO_NOLOOP(result, foo(bar), ok)
237  *            {
238  *            }
239  *      }
240  *
241  *   if (!ok)
242  *     {
243  *        // Something failed, cleanup.
244  *     }
245  */
246         switch (saved_errno)
247           {
248            case EACCES:
249            case EAGAIN:
250            case EINTR:
251                { /* Not now, try later. */
252                   ERR("*** Must try again in %s @%u.", file, line);
253                   result = -1;
254                   break;
255                }
256            case EMFILE:
257            case ENFILE:
258            case ENOLCK:
259                { /* Low on resources. */
260                   ERR("*** Low on resources in %s @%u.", file,
261                       line);
262                   result = 0;
263                   break;
264                }
265            case EIO:
266                { /* I/O error. */
267                   ERR("*** I/O error in %s @%u.", file, line);
268                   result = 0;
269                   break;
270                }
271            case EFAULT:
272            case EBADF:
273            case EINVAL:
274            case EROFS:
275            case EISDIR:
276            case EDEADLK:
277            case EPERM:
278            case EBUSY:
279                { /* Programmer fucked up. */
280                   ERR("*** NAUGHTY PROGRAMMER!!!\n"
281                       "*** SPANK SPANK SPANK!!!\n"
282                       "*** Now go fix your code in %s @%u. Tut tut tut!",
283                       file, line);
284                   result = 0;
285                   break;
286                }
287            default:
288                { /* Unsupported errno code, please add this one. */
289                   ERR("*** NAUGHTY PROGRAMMER!!!\n"
290                       "*** SPANK SPANK SPANK!!!\n"
291                       "*** Unsupported errno code %d, please add this one.\n"
292                       "*** Now go fix your code in %s @%u, from %s @%u. Tut tut tut!",
293                       saved_errno, __FILE__, __LINE__, file, line);
294                   result = 0;
295                   break;
296                }
297           }
298      }
299    else /* Everything is fine. */
300      result = 1;
301
302    errno = saved_errno;
303    return result;
304 }
305
306 /**
307  * @defgroup Ecore_Exe_Basic_Group Process Spawning Functions
308  *
309  * Functions that deal with spawned processes.
310  */
311
312 static int run_pri = ECORE_EXE_PRIORITY_INHERIT;
313
314 /**
315  * Sets the priority at which to launch processes
316  *
317  * This sets the priority of processes run by ecore_exe_run() and
318  * ecore_exe_pipe_run().
319  * @li On Windows, the child process is created by default with the
320  * #ECORE_EXE_WIN32_PRIORITY_NORMAL priority, unless the calling
321  * process is in #ECORE_EXE_WIN32_PRIORITY_IDLE or
322  * #ECORE_EXE_WIN32_PRIORITY_BELOW_NORMAL priority. In that case, the
323  * child process inherits this priority.
324  * @li On other platforms, if set to #ECORE_EXE_PRIORITY_INHERIT child
325  * processes inherits the priority of their parent. This is the default.
326  *
327  * @param   pri value a Ecore_Exe_Win32_Priority value on Windows, -20
328  * to 19 or ECORE_EXE_PRIORITY_INHERIT on other OS.
329  * @ingroup Ecore_Exe_Basic_Group
330  */
331 EAPI void
332 ecore_exe_run_priority_set(int pri)
333 {
334    run_pri = pri;
335 }
336
337 /**
338  * Gets the priority at which to launch processes
339  *
340  * This gets ths priority of launched processes. See
341  * ecore_exe_run_priority_set() for details. This just returns the value set
342  * by this call.
343  *
344  * @return the value set by ecore_exe_run_priority_set()
345  * @ingroup Ecore_Exe_Basic_Group
346  */
347 EAPI int
348 ecore_exe_run_priority_get(void)
349 {
350    return run_pri;
351 }
352
353 /**
354  * Spawns a child process.
355  *
356  * This is now just a thin wrapper around ecore_exe_pipe_run()
357  *
358  * @param   exe_cmd The command to run with @c /bin/sh.
359  * @param   data    Data to attach to the returned process handle.
360  * @return  A process handle to the spawned process.
361  * @ingroup Ecore_Exe_Basic_Group
362  */
363 EAPI Ecore_Exe *
364 ecore_exe_run(const char *exe_cmd, const void *data)
365 {
366 /* I'm just being paranoid again, leaving in the original code in case there is a problem. */
367 #if 0
368    Ecore_Exe *exe;
369    pid_t pid;
370
371    if (!exe_cmd)
372       return NULL;
373    pid = fork();
374    if (pid)
375      {
376         exe = calloc(1, sizeof(Ecore_Exe));
377         if (!exe)
378           {
379              kill(pid, SIGKILL);
380              return NULL;
381           }
382         ECORE_MAGIC_SET(exe, ECORE_MAGIC_EXE);
383         exe->pid = pid;
384         exe->data = (void *)data;
385         exe->cmd = strdup(exe_cmd);
386         exes = _ecore_list2_append(exes, exe);
387         return exe;
388      }
389    _ecore_exe_exec_it(exe_cmd, 0);
390    exit(127);
391    return NULL;
392 #else
393    return ecore_exe_pipe_run(exe_cmd, 0, data);
394 #endif
395 }
396
397 /**
398  * Spawns a child process with its stdin/out available for communication.
399  *
400  * This function forks and runs the given command using @c /bin/sh.
401  *
402  * Note that the process handle is only valid until a child process
403  * terminated event is received.  After all handlers for the child process
404  * terminated event have been called, the handle will be freed by Ecore.
405  *
406  * This function does the same thing as ecore_exe_run(), but also makes the
407  * standard in and/or out as well as stderr from the child process available
408  * for reading or writing.  To write use ecore_exe_send().  To read listen to
409  * ECORE_EXE_EVENT_DATA or ECORE_EXE_EVENT_ERROR events (set up handlers).
410  * Ecore may buffer read and error data until a newline character if asked
411  * for with the @p flags.  All data will be included in the events (newlines
412  * will be replaced with NULLS if line buffered).  ECORE_EXE_EVENT_DATA events
413  * will only happen if the process is run with ECORE_EXE_PIPE_READ enabled
414  * in the flags.  The same with the error version.  Writing will only be
415  * allowed with ECORE_EXE_PIPE_WRITE enabled in the flags.
416  *
417  * @param   exe_cmd The command to run with @c /bin/sh.
418  * @param   flags   The flag parameters for how to deal with inter-process I/O
419  * @param   data    Data to attach to the returned process handle.
420  * @return  A process handle to the spawned process.
421  * @ingroup Ecore_Exe_Basic_Group
422  */
423 EAPI Ecore_Exe *
424 ecore_exe_pipe_run(const char *exe_cmd, Ecore_Exe_Flags flags, const void *data)
425 {
426    Ecore_Exe *exe = NULL;
427    int statusPipe[2] = { -1, -1 };
428    int errorPipe[2] = { -1, -1 };
429    int readPipe[2] = { -1, -1 };
430    int writePipe[2] = { -1, -1 };
431    int n = 0;
432    int ok = 1;
433    int result;
434
435    if (!exe_cmd) return NULL;
436    exe = calloc(1, sizeof(Ecore_Exe));
437    if (exe == NULL) return NULL;
438
439    if ((flags & ECORE_EXE_PIPE_AUTO) && (!(flags & ECORE_EXE_PIPE_ERROR))
440        && (!(flags & ECORE_EXE_PIPE_READ)))
441      /* We need something to auto pipe. */
442      flags |= ECORE_EXE_PIPE_READ | ECORE_EXE_PIPE_ERROR;
443
444    exe->child_fd_error = -1;
445    exe->child_fd_read = -1;
446    exe->child_fd_write = -1;
447    exe->child_fd_error_x = -1;
448    exe->child_fd_read_x = -1;
449    exe->child_fd_write_x = -1;
450
451    /*  Create some pipes. */
452    if (ok)
453      {
454         E_IF_NO_ERRNO_NOLOOP(result, pipe(statusPipe), ok)
455           {
456           }
457      }
458    if (ok && (flags & ECORE_EXE_PIPE_ERROR))
459      {
460         E_IF_NO_ERRNO_NOLOOP(result, pipe(errorPipe), ok)
461           {
462              exe->child_fd_error = errorPipe[0];
463              exe->child_fd_error_x = errorPipe[1];
464           }
465      }
466    if (ok && (flags & ECORE_EXE_PIPE_READ))
467      {
468         E_IF_NO_ERRNO_NOLOOP(result, pipe(readPipe), ok)
469           {
470              exe->child_fd_read = readPipe[0];
471              exe->child_fd_read_x = readPipe[1];
472           }
473      }
474    if (ok && (flags & ECORE_EXE_PIPE_WRITE))
475      {
476         E_IF_NO_ERRNO_NOLOOP(result, pipe(writePipe), ok)
477           {
478              exe->child_fd_write = writePipe[1];
479              exe->child_fd_write_x = writePipe[0];
480           }
481      }
482    if (ok)
483      {
484         pid_t pid = 0;
485         volatile int vfork_exec_errno = 0;
486
487         /* FIXME: I should double check this.  After a quick look around, this is already done, but via a more modern method. */
488         /* signal(SIGPIPE, SIG_IGN);    We only want EPIPE on errors */
489         pid = fork();
490
491         if (pid == -1)
492           {
493              ERR("Failed to fork process");
494              pid = 0;
495           }
496         else if (pid == 0)      /* child */
497           {
498              if (run_pri != ECORE_EXE_PRIORITY_INHERIT)
499                {
500                   if ((run_pri >= -20) && (run_pri <= 19))
501                     setpriority(PRIO_PROCESS, 0, run_pri);
502                }
503              /* dup2 STDERR, STDIN, and STDOUT.  dup2() allegedly closes the
504               * second pipe if it's open. On the other hand, there was the
505               * Great FD Leak Scare of '06, so let's be paranoid. */
506              if (ok && (flags & ECORE_EXE_PIPE_ERROR))
507                {
508                   E_NO_ERRNO(result, close(STDERR_FILENO), ok);
509                   E_NO_ERRNO(result, dup2(errorPipe[1], STDERR_FILENO), ok);
510                }
511              if (ok && (flags & ECORE_EXE_PIPE_READ))
512                {
513                   E_NO_ERRNO(result, close(STDOUT_FILENO), ok);
514                   E_NO_ERRNO(result, dup2(readPipe[1], STDOUT_FILENO), ok);
515                }
516              if (ok && (flags & ECORE_EXE_PIPE_WRITE))
517                {
518                   E_NO_ERRNO(result, close(STDIN_FILENO), ok);
519                   E_NO_ERRNO(result, dup2(writePipe[0], STDIN_FILENO), ok);
520                }
521
522              if (ok)
523                {
524                   /* Setup the status pipe. */
525                   E_NO_ERRNO(result, close(statusPipe[0]), ok);
526                   E_IF_NO_ERRNO(result, fcntl(statusPipe[1], F_SETFD, FD_CLOEXEC), ok)  /* close on exec shows sucess */
527                     {
528                        /* Run the actual command. */
529                        _ecore_exe_exec_it(exe_cmd, flags); /* no return */
530                     }
531                }
532
533              /* Something went 'orribly wrong. */
534              vfork_exec_errno = errno;
535
536              /* Close the pipes. */
537              if (flags & ECORE_EXE_PIPE_ERROR)
538                E_NO_ERRNO(result, close(errorPipe[1]), ok);
539              if (flags & ECORE_EXE_PIPE_READ)
540                E_NO_ERRNO(result, close(readPipe[1]), ok);
541              if (flags & ECORE_EXE_PIPE_WRITE)
542                E_NO_ERRNO(result, close(writePipe[0]), ok);
543              E_NO_ERRNO(result, close(statusPipe[1]), ok);
544
545              _exit(-1);
546           }
547         else /* parent */
548           {
549              /* Close the unused pipes. */
550              E_NO_ERRNO(result, close(statusPipe[1]), ok);
551
552              /* FIXME: after having a good look at the current e fd
553               * handling, investigate fcntl(dataPipe[x], F_SETSIG, ...) */
554              /* FIXME: above F_SETSIG etc. - this is async SIGIO based IO
555               * which is also linux specific so we probably don't want to
556               * do this as long as select() is working fine. the only time
557               * we really want to think of SIGIO async IO is when it all
558               * actually works basically everywhere and we can turn all
559               * IO into DMA async activities (i.e. you do a read() then
560               * the read is complete not on return but when you get a
561               * SIGIO - the read() just starts the transfer and it is
562               * completed in the background by DMA (or whatever mechanism
563               * the kernel choses)) */
564
565              /* Wait for it to start executing. */
566              /* FIXME: this doesn't seem very nice - we sit and block
567               * waiting on a child process... even though it's just
568               * the segment between the fork() and the exec) it just feels
569               * wrong */
570              for (;;)
571                {
572                   char buf;
573
574                   E_NO_ERRNO(result, read(statusPipe[0], &buf, 1), ok);
575                   if (result == 0)
576                     {
577                        if (vfork_exec_errno != 0)
578                          {
579                             n = vfork_exec_errno;
580                             ERR("Could not start \"%s\"", exe_cmd);
581                             pid = 0;
582                          }
583                        break;
584                     }
585                }
586
587              /* Close the status pipe. */
588              E_NO_ERRNO(result, close(statusPipe[0]), ok);
589           }
590
591         if (pid)
592           {
593              /* Setup the exe structure. */
594              ECORE_MAGIC_SET(exe, ECORE_MAGIC_EXE);
595              exe->start_bytes = -1;
596              exe->end_bytes = -1;
597              exe->start_lines = -1;
598              exe->end_lines = -1;
599              exe->pid = pid;
600              exe->flags = flags;
601              exe->data = (void *)data;
602              if ((exe->cmd = strdup(exe_cmd)))
603                {
604                   if (flags & ECORE_EXE_PIPE_ERROR)
605                     { /* Setup the error stuff. */
606                        E_IF_NO_ERRNO(result,
607                                      fcntl(exe->child_fd_error, F_SETFL,
608                                            O_NONBLOCK), ok) {}
609                        E_IF_NO_ERRNO(result,
610                                      fcntl(exe->child_fd_error, F_SETFD,
611                                            FD_CLOEXEC), ok) {}
612                        E_IF_NO_ERRNO(result,
613                                      fcntl(exe->child_fd_error_x, F_SETFD,
614                                            FD_CLOEXEC), ok) {}
615                        {
616                           exe->error_fd_handler =
617                              ecore_main_fd_handler_add(exe->child_fd_error,
618                                                        ECORE_FD_READ,
619                                                        _ecore_exe_data_error_handler,
620                                                        exe, NULL, NULL);
621                           if (exe->error_fd_handler == NULL)
622                              ok = 0;
623                        }
624                     }
625                   if (ok && (flags & ECORE_EXE_PIPE_READ))
626                     { /* Setup the read stuff. */
627                        E_IF_NO_ERRNO(result,
628                                      fcntl(exe->child_fd_read, F_SETFL,
629                                            O_NONBLOCK), ok) {}
630                        E_IF_NO_ERRNO(result,
631                                      fcntl(exe->child_fd_read, F_SETFD,
632                                            FD_CLOEXEC), ok) {}
633                        E_IF_NO_ERRNO(result,
634                                      fcntl(exe->child_fd_read_x, F_SETFD,
635                                            FD_CLOEXEC), ok) {}
636                        {
637                           exe->read_fd_handler =
638                              ecore_main_fd_handler_add(exe->child_fd_read,
639                                                        ECORE_FD_READ,
640                                                        _ecore_exe_data_read_handler,
641                                                        exe, NULL, NULL);
642                           if (exe->read_fd_handler == NULL)
643                              ok = 0;
644                        }
645                     }
646                   if (ok && (flags & ECORE_EXE_PIPE_WRITE))
647                     {           /* Setup the write stuff. */
648                        E_IF_NO_ERRNO(result,
649                                      fcntl(exe->child_fd_write, F_SETFL,
650                                            O_NONBLOCK), ok) {}
651                        E_IF_NO_ERRNO(result,
652                                      fcntl(exe->child_fd_write, F_SETFD,
653                                            FD_CLOEXEC), ok) {}
654                        E_IF_NO_ERRNO(result,
655                                      fcntl(exe->child_fd_write_x, F_SETFD,
656                                            FD_CLOEXEC), ok) {}
657                        {
658                           exe->write_fd_handler =
659                              ecore_main_fd_handler_add(exe->child_fd_write,
660                                                        ECORE_FD_WRITE,
661                                                        _ecore_exe_data_write_handler,
662                                                        exe, NULL, NULL);
663                           if (exe->write_fd_handler)
664                              ecore_main_fd_handler_active_set(exe->write_fd_handler, 0);        /* Nothing to write to start with. */
665                           else
666                              ok = 0;
667                        }
668                     }
669
670                   exes = (Ecore_Exe *) eina_inlist_append(EINA_INLIST_GET(exes), EINA_INLIST_GET(exe));
671                   n = 0;
672                }
673              else
674                ok = 0;
675           }
676         else
677           ok = 0;
678      }
679
680    if (!ok)
681      { /* Something went wrong, so pull down everything. */
682         if (exe->pid) ecore_exe_terminate(exe);
683         IF_FN_DEL(ecore_exe_free, exe);
684      }
685    else
686      {
687         Ecore_Exe_Event_Add *e;
688
689         e = _ecore_exe_event_add_new();
690         e->exe = exe;
691         if (e) /* Send the event. */
692           ecore_event_add(ECORE_EXE_EVENT_ADD, e,
693                           _ecore_exe_event_add_free, NULL);
694         /* INF("Running as %d for %s.\n", exe->pid, exe->cmd); */
695      }
696
697    errno = n;
698    return exe;
699 }
700
701 /**
702  * Defines a function to be called before really freeing the handle data.
703  *
704  * This might be useful for language bindings such as Python and Perl
705  * that need to deallocate wrappers associated with this handle.
706  *
707  * This handle should never be modified by this call. It should be
708  * considered informative only. All getters are valid when the given
709  * function is called back.
710  *
711  * @param exe The child process to attach the pre_free function.
712  * @param func The function to call before @a exe is freed.
713  */
714 EAPI void
715 ecore_exe_callback_pre_free_set(Ecore_Exe *exe, void (*func)(void *data, const Ecore_Exe *exe))
716 {
717    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
718      {
719         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE,
720                          "ecore_exe_callback_pre_free_set");
721         return;
722      }
723    exe->pre_free_cb = func;
724 }
725
726 /**
727  * Sends data to the given child process which it recieves on stdin.
728  *
729  * This function writes to a child processes standard in, with unlimited
730  * buffering. This call will never block. It may fail if the system runs out
731  * of memory.
732  *
733  * @param exe  The child process to send to
734  * @param data The data to send
735  * @param size The size of the data to send, in bytes
736  * @return EINA_TRUE if successful, EINA_FALSE on failure.
737  * @ingroup Ecore_Exe_Basic_Group
738  */
739 EAPI Eina_Bool
740 ecore_exe_send(Ecore_Exe * exe, const void *data, int size)
741 {
742    void *buf;
743
744    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
745      {
746         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_send");
747         return 0;
748      }
749
750    if (exe->close_stdin)
751      {
752         ERR("Ecore_Exe %p stdin is closed! Cannot send %d bytes from %p",
753             exe, size, data);
754         return 0;
755      }
756
757    if (exe->child_fd_write == -1)
758      {
759         ERR("Ecore_Exe %p created without ECORE_EXE_PIPE_WRITE! "
760             "Cannot send %d bytes from %p", exe, size, data);
761         return 0;
762      }
763
764    buf = realloc(exe->write_data_buf, exe->write_data_size + size);
765    if (buf == NULL) return 0;
766
767    exe->write_data_buf = buf;
768    memcpy((char *)exe->write_data_buf + exe->write_data_size, data, size);
769    exe->write_data_size += size;
770
771    if (exe->write_fd_handler)
772       ecore_main_fd_handler_active_set(exe->write_fd_handler, ECORE_FD_WRITE);
773
774    return 1;
775 }
776
777 /**
778  * The stdin of the given child process will close when the write buffer is empty.
779  *
780  * @param exe  The child process
781  * @ingroup Ecore_Exe_Basic_Group
782  */
783 EAPI void
784 ecore_exe_close_stdin(Ecore_Exe *exe)
785 {
786    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
787      {
788         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_close_stdin");
789         return;
790      }
791    exe->close_stdin = 1;
792 }
793
794 /**
795  * Sets the auto pipe limits for the given process handle. On Windows
796  * this function does nothing.
797  *
798  * @param   exe The given process handle.
799  * @param   start_bytes limit of bytes at start of output to buffer.
800  * @param   end_bytes limit of bytes at end of output to buffer.
801  * @param   start_lines limit of lines at start of output to buffer.
802  * @param   end_lines limit of lines at end of output to buffer.
803  * @ingroup Ecore_Exe_Basic_Group
804  */
805 EAPI void
806 ecore_exe_auto_limits_set(Ecore_Exe *exe, int start_bytes, int end_bytes, int start_lines, int end_lines)
807 {
808    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
809      {
810         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_auto_limits_set");
811         return;
812      }
813    /* FIXME: sanitize the input. */
814    exe->start_bytes = start_bytes;
815    exe->end_bytes = end_bytes;
816    exe->start_lines = start_lines;
817    exe->end_lines = end_lines;
818
819    /* FIXME: get this can of worms working.
820     *
821     * capture stderr & stdout internally
822     *
823     * raster and onefang keep moving the goal posts on this one.  It started out as
824     * "show users the error output if an exe fails" and is rapidly approaching
825     * "alternative method of getting the data, poll vs event driven".  Some serious
826     * thinking needs to be applied to this.  Do we really want to go that far?  If
827     * so, we should change the names.  The basic design will probably remain the
828     * same which ever way we go.  The constant goal post moving is probably due to
829     * generic design methods leading to feature creep as we inspired each other to
830     * more generic designs.  It does seem like the closer we get to poll driven,
831     * the more issues and corner cases there are.
832     *
833     * Instead of doing the usual register an event handler thing, we are ecore_exe,
834     * we can take some short cuts.  Don't send the events, just leave the exe buffers
835     * as is until the user asks for them, then return the event.
836     *
837     * start = 0,  end = 0;   clogged arteries get flushed, everything is ignored.
838     * start = -1, end = -1;  clogged arteries get transferred to internal buffers.  Actually, either == -1 means buffer everything.
839     * start = X,  end = 0;   buffer first X out of clogged arteries, flush and ignore rest.
840     * start = 0,  end = X;   circular buffer X
841     * start = X,  end = Y;   buffer first X out of clogged arteries, circular buffer Y from beginning.
842     *
843     * bytes vs lines, which ever one reaches the limit first.
844     * Before we go beyond the start+end limit, leave the end buffer empty, and store both in the start buffer, coz they overlap.
845     * 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.
846     *
847     * Other issues -
848     * Spank programmer for polling data if polling is not turned on.
849     * Spank programmer for setting up event callbacks if polling is turned on.
850     * Spank programmer for freeing the event data if it came from the event system, as that autofrees.
851     * Spank the programmer if they try to set the limits bigger than what has been gathered & ignored already, coz they just lost data.
852     * Spank onefang and raster for opening this can of worms.
853     * Should we have seperate out/err limits?
854     * Should we remove from the internal buffer the data that was delivered already?
855     * If so, what to do about limits, start, and end?  They could loose their meaning.
856     */
857 }
858
859 /**
860  * Gets the auto pipe data for the given process handle
861  *
862  * @param   exe The given process handle.
863  * @param   flags   Is this a ECORE_EXE_PIPE_READ or ECORE_EXE_PIPE_ERROR?
864  * @ingroup Ecore_Exe_Basic_Group
865  */
866 EAPI Ecore_Exe_Event_Data *
867 ecore_exe_event_data_get(Ecore_Exe *exe, Ecore_Exe_Flags flags)
868 {
869    Ecore_Exe_Event_Data *e = NULL;
870    int is_buffered = 0;
871    unsigned char *inbuf;
872    int inbuf_num;
873
874    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
875      {
876         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_event_data_get");
877         return NULL;
878      }
879
880    /* Sort out what sort of event we are. */
881    if (flags & ECORE_EXE_PIPE_READ)
882      {
883         flags = ECORE_EXE_PIPE_READ;
884         if (exe->flags & ECORE_EXE_PIPE_READ_LINE_BUFFERED)
885            is_buffered = 1;
886      }
887    else
888      {
889         flags = ECORE_EXE_PIPE_ERROR;
890         if (exe->flags & ECORE_EXE_PIPE_ERROR_LINE_BUFFERED)
891            is_buffered = 1;
892      }
893
894    /* Get the data. */
895    if (flags & ECORE_EXE_PIPE_READ)
896      {
897         inbuf = exe->read_data_buf;
898         inbuf_num = exe->read_data_size;
899         exe->read_data_buf = NULL;
900         exe->read_data_size = 0;
901      }
902    else
903      {
904         inbuf = exe->error_data_buf;
905         inbuf_num = exe->error_data_size;
906         exe->error_data_buf = NULL;
907         exe->error_data_size = 0;
908      }
909
910    e = calloc(1, sizeof(Ecore_Exe_Event_Data));
911    if (e)
912      {
913         e->exe = exe;
914         e->data = inbuf;
915         e->size = inbuf_num;
916
917         if (is_buffered)
918           {                     /* Deal with line buffering. */
919              int max = 0;
920              int count = 0;
921              int i;
922              int last = 0;
923              char *c;
924
925              c = (char *)inbuf;
926              for (i = 0; i < inbuf_num; i++)    /* Find the lines. */
927                {
928                   if (inbuf[i] == '\n')
929                     {
930                        if (count >= max)
931                          {
932                             /* In testing, the lines seem to arrive in batches of 500 to 1000 lines at most, roughly speaking. */
933                             max += 10;  /* FIXME: Maybe keep track of the largest number of lines ever sent, and add half that many instead of 10. */
934                             e->lines = realloc(e->lines, sizeof(Ecore_Exe_Event_Data_Line) * (max + 1));        /* Allow room for the NULL termination. */
935                          }
936                        /* raster said to leave the line endings as line endings, however -
937                         * This is line buffered mode, we are not dealing with binary here, but lines.
938                         * If we are not dealing with binary, we must be dealing with ASCII, unicode, or some other text format.
939                         * Thus the user is most likely gonna deal with this text as strings.
940                         * Thus the user is most likely gonna pass this data to str functions.
941                         * rasters way - the endings are always gonna be '\n';  onefangs way - they will always be '\0'
942                         * We are handing them the string length as a convenience.
943                         * Thus if they really want it in raw format, they can e->lines[i].line[e->lines[i].size - 1] = '\n'; easily enough.
944                         * In the default case, we can do this conversion quicker than the user can, as we already have the index and pointer.
945                         * Let's make it easy on them to use these as standard C strings.
946                         *
947                         * onefang is proud to announce that he has just set a new personal record for the
948                         * most over documentation of a simple assignment statement.  B-)
949                         */
950                        inbuf[i] = '\0';
951                        e->lines[count].line = c;
952                        e->lines[count].size = i - last;
953                        last = i + 1;
954                        c = (char *)&inbuf[last];
955                        count++;
956                     }
957                }
958              if (count == 0)    /* No lines to send, cancel the event. */
959                {
960                   _ecore_exe_event_exe_data_free(NULL, e);
961                   e = NULL;
962                }
963              else               /* NULL terminate the array, so that people know where the end is. */
964                {
965                   e->lines[count].line = NULL;
966                   e->lines[count].size = 0;
967                }
968              if (i > last)      /* Partial line left over, save it for next time. */
969                {
970                   if (e) e->size = last;
971                   if (flags & ECORE_EXE_PIPE_READ)
972                     {
973                        exe->read_data_size = i - last;
974                        exe->read_data_buf = malloc(exe->read_data_size);
975                        memcpy(exe->read_data_buf, c, exe->read_data_size);
976                     }
977                   else
978                     {
979                        exe->error_data_size = i - last;
980                        exe->error_data_buf = malloc(exe->error_data_size);
981                        memcpy(exe->error_data_buf, c, exe->error_data_size);
982                     }
983                }
984           }
985      }
986
987    return e;
988 }
989
990 /**
991  * Sets the string tag for the given process handle
992  *
993  * @param   exe The given process handle.
994  * @param   tag The string tag to set on the process handle.
995  * @ingroup Ecore_Exe_Basic_Group
996  */
997 EAPI void
998 ecore_exe_tag_set(Ecore_Exe *exe, const char *tag)
999 {
1000    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1001      {
1002         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_tag_set");
1003         return;
1004      }
1005    IF_FREE(exe->tag);
1006    if (tag)
1007       exe->tag = strdup(tag);
1008    else
1009       exe->tag = NULL;
1010 }
1011
1012 /**
1013  * Retrieves the tag attached to the given process handle. There is no need to
1014  * free it as it just returns the internal pointer value. This value is only
1015  * valid as long as the @p exe is valid or until the tag is set to something
1016  * else on this @p exe.
1017  *
1018  * @param   exe The given process handle.
1019  * @return The string attached to @p exe. It is a handle to existing
1020  *         internal string and should not be modified, use
1021  *         ecore_exe_tag_set() to change it. It might be @c NULL.
1022  * @ingroup Ecore_Exe_Basic_Group
1023  */
1024 EAPI const char *
1025 ecore_exe_tag_get(const Ecore_Exe *exe)
1026 {
1027    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1028      {
1029         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_tag_get");
1030         return NULL;
1031      }
1032    return exe->tag;
1033 }
1034
1035 /**
1036  * Frees the given process handle.
1037  *
1038  * Note that the process that the handle represents is unaffected by this
1039  * function.
1040  *
1041  * @param   exe The given process handle.
1042  * @return  The data attached to the handle when @ref ecore_exe_run was
1043  *          called.
1044  * @ingroup Ecore_Exe_Basic_Group
1045  */
1046 EAPI void *
1047 ecore_exe_free(Ecore_Exe *exe)
1048 {
1049    void *data;
1050    int ok = 0;
1051    int result;
1052
1053    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1054      {
1055         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_free");
1056         return NULL;
1057      }
1058
1059    data = exe->data;
1060
1061    if (exe->pre_free_cb)
1062      exe->pre_free_cb(data, exe);
1063
1064    if (exe->doomsday_clock)
1065      {
1066         struct _ecore_exe_dead_exe *dead;
1067
1068         ecore_timer_del(exe->doomsday_clock);
1069         exe->doomsday_clock = NULL;
1070         dead = exe->doomsday_clock_dead;
1071         if (dead)
1072           {
1073              IF_FREE(dead->cmd);
1074              free(dead);
1075              exe->doomsday_clock_dead = NULL;
1076           }
1077      }
1078    IF_FN_DEL(ecore_main_fd_handler_del, exe->write_fd_handler);
1079    IF_FN_DEL(ecore_main_fd_handler_del, exe->read_fd_handler);
1080    IF_FN_DEL(ecore_main_fd_handler_del, exe->error_fd_handler);
1081    if (exe->child_fd_write_x != -1)
1082       E_NO_ERRNO(result, close(exe->child_fd_write_x), ok);
1083    if (exe->child_fd_read_x != -1)
1084       E_NO_ERRNO(result, close(exe->child_fd_read_x), ok);
1085    if (exe->child_fd_error_x != -1)
1086       E_NO_ERRNO(result, close(exe->child_fd_error_x), ok);
1087    if (exe->child_fd_write != -1)
1088       E_NO_ERRNO(result, close(exe->child_fd_write), ok);
1089    if (exe->child_fd_read != -1)
1090       E_NO_ERRNO(result, close(exe->child_fd_read), ok);
1091    if (exe->child_fd_error != -1)
1092       E_NO_ERRNO(result, close(exe->child_fd_error), ok);
1093    IF_FREE(exe->write_data_buf);
1094    IF_FREE(exe->read_data_buf);
1095    IF_FREE(exe->error_data_buf);
1096    IF_FREE(exe->cmd);
1097
1098    exes = (Ecore_Exe *) eina_inlist_remove(EINA_INLIST_GET(exes), EINA_INLIST_GET(exe));
1099    ECORE_MAGIC_SET(exe, ECORE_MAGIC_NONE);
1100    IF_FREE(exe->tag);
1101    free(exe);
1102    return data;
1103 }
1104
1105 /**
1106  * Frees the given event data.
1107  *
1108  * @param   e The given event data.
1109  * @ingroup Ecore_Exe_Basic_Group
1110  */
1111 EAPI void
1112 ecore_exe_event_data_free(Ecore_Exe_Event_Data *e)
1113 {
1114    if (!e) return;
1115    IF_FREE(e->lines);
1116    IF_FREE(e->data);
1117    free(e);
1118 }
1119
1120 /**
1121  * Retrieves the process ID of the given spawned process.
1122  * @param   exe Handle to the given spawned process.
1123  * @return  The process ID on success.  @c -1 otherwise.
1124  * @ingroup Ecore_Exe_Basic_Group
1125  */
1126 EAPI pid_t
1127 ecore_exe_pid_get(const Ecore_Exe *exe)
1128 {
1129    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1130      {
1131         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_pid_get");
1132         return -1;
1133      }
1134    return exe->pid;
1135 }
1136
1137 /**
1138  * Retrieves the command of the given spawned process.
1139  * @param   exe Handle to the given spawned process.
1140  * @return The command on success.  NULL otherwise. This string is the
1141  *         pointer to the internal value and must not be modified in
1142  *         any way.
1143  * @ingroup Ecore_Exe_Basic_Group
1144  */
1145 EAPI const char *
1146 ecore_exe_cmd_get(const Ecore_Exe *exe)
1147 {
1148    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1149      {
1150         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_cmd_get");
1151         return NULL;
1152      }
1153    return exe->cmd;
1154 }
1155
1156 /**
1157  * Retrieves the data attached to the given process handle.
1158  * @param   exe The given process handle.
1159  * @return The data pointer attached to @p exe Given to
1160  *         ecore_exe_run() or ecore_exe_pipe_run()
1161  * @ingroup Ecore_Exe_Basic_Group
1162  */
1163 EAPI void *
1164 ecore_exe_data_get(const Ecore_Exe *exe)
1165 {
1166    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1167      {
1168         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_data_get");
1169         return NULL;
1170      }
1171    return exe->data;
1172 }
1173
1174 /**
1175  * Retrieves the flags attached to the given process handle.
1176  * @param   exe The given process handle.
1177  * @return  The flags attached to @p exe.
1178  * @ingroup Ecore_Exe_Basic_Group
1179  */
1180 EAPI Ecore_Exe_Flags
1181 ecore_exe_flags_get(const Ecore_Exe *exe)
1182 {
1183    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1184      {
1185         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_data_get");
1186         return 0;
1187      }
1188    return exe->flags;
1189 }
1190
1191 /**
1192  * @defgroup Ecore_Exe_Signal_Group Spawned Process Signal Functions
1193  *
1194  * Functions that send signals to spawned processes.
1195  */
1196
1197 /**
1198  * Pauses the given process by sending it a @c SIGSTOP signal.
1199  * @param   exe Process handle to the given process.
1200  * @ingroup Ecore_Exe_Signal_Group
1201  */
1202 EAPI void
1203 ecore_exe_pause(Ecore_Exe *exe)
1204 {
1205    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1206      {
1207         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_pause");
1208         return;
1209      }
1210    kill(exe->pid, SIGSTOP);
1211 }
1212
1213 /**
1214  * Continues the given paused process by sending it a @c SIGCONT signal.
1215  * @param   exe Process handle to the given process.
1216  * @ingroup Ecore_Exe_Signal_Group
1217  */
1218 EAPI void
1219 ecore_exe_continue(Ecore_Exe *exe)
1220 {
1221    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1222      {
1223         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_continue");
1224         return;
1225      }
1226    kill(exe->pid, SIGCONT);
1227 }
1228
1229 /**
1230  * Sends the given spawned process a interrupt (@c SIGINT) signal.
1231  * @param   exe Process handle to the given process.
1232  * @ingroup Ecore_Exe_Signal_Group
1233  */
1234 EAPI void
1235 ecore_exe_interrupt(Ecore_Exe *exe)
1236 {
1237    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1238      {
1239         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_interrupt");
1240         return;
1241      }
1242    _ecore_exe_dead_attach(exe);
1243    kill(exe->pid, SIGINT);
1244 }
1245
1246 /**
1247  * Sends the given spawned process a quit (@c SIGQUIT) signal.
1248  * @param   exe Process handle to the given process.
1249  * @ingroup Ecore_Exe_Signal_Group
1250  */
1251 EAPI void
1252 ecore_exe_quit(Ecore_Exe *exe)
1253 {
1254    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1255      {
1256         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_quit");
1257         return;
1258      }
1259    _ecore_exe_dead_attach(exe);
1260    kill(exe->pid, SIGQUIT);
1261 }
1262
1263 /**
1264  * Sends the given spawned process a terminate (@c SIGTERM) signal.
1265  * @param   exe Process handle to the given process.
1266  * @ingroup Ecore_Exe_Signal_Group
1267  */
1268 EAPI void
1269 ecore_exe_terminate(Ecore_Exe *exe)
1270 {
1271    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1272      {
1273         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_terminate");
1274         return;
1275      }
1276    _ecore_exe_dead_attach(exe);
1277    INF("Sending TERM signal to %s (%d).", exe->cmd, exe->pid);
1278    kill(exe->pid, SIGTERM);
1279 }
1280
1281 /**
1282  * Kills the given spawned process by sending it a @c SIGKILL signal.
1283  * @param   exe Process handle to the given process.
1284  * @ingroup Ecore_Exe_Signal_Group
1285  */
1286 EAPI void
1287 ecore_exe_kill(Ecore_Exe *exe)
1288 {
1289    struct _ecore_exe_dead_exe *dead;
1290
1291    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1292      {
1293         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_kill");
1294         return;
1295      }
1296
1297    dead = calloc(1, sizeof(struct _ecore_exe_dead_exe));
1298    if (dead)
1299      {
1300         dead->pid = exe->pid;
1301         dead->cmd = strdup(exe->cmd);
1302         IF_FN_DEL(ecore_timer_del, exe->doomsday_clock);
1303         exe->doomsday_clock =
1304            ecore_timer_add(10.0, _ecore_exe_make_sure_its_really_dead, dead);
1305      }
1306
1307    INF("Sending KILL signal to %s (%d).", exe->cmd, exe->pid);
1308    kill(exe->pid, SIGKILL);
1309 }
1310
1311 /**
1312  * Sends a @c SIGUSR signal to the given spawned process.
1313  * @param   exe Process handle to the given process.
1314  * @param   num The number user signal to send.  Must be either 1 or 2, or
1315  *              the signal will be ignored.
1316  * @ingroup Ecore_Exe_Signal_Group
1317  */
1318 EAPI void
1319 ecore_exe_signal(Ecore_Exe *exe, int num)
1320 {
1321    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1322      {
1323         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_signal");
1324         return;
1325      }
1326    if (num == 1)
1327       kill(exe->pid, SIGUSR1);
1328    else if (num == 2)
1329       kill(exe->pid, SIGUSR2);
1330 }
1331
1332 /**
1333  * Sends a @c SIGHUP signal to the given spawned process.
1334  * @param   exe Process handle to the given process.
1335  * @ingroup Ecore_Exe_Signal_Group
1336  */
1337 EAPI void
1338 ecore_exe_hup(Ecore_Exe *exe)
1339 {
1340    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1341      {
1342         ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_hup");
1343         return;
1344      }
1345    kill(exe->pid, SIGHUP);
1346 }
1347
1348 static Ecore_Exe *
1349 _ecore_exe_is_it_alive(pid_t pid)
1350 {
1351    Ecore_Exe *exe = NULL;
1352
1353    /* FIXME: There is no nice, safe, OS independant way to tell if a
1354     * particular PID is still alive.  I have written code to do so
1355     * for my urunlevel busybox applet (http://urunlevel.sourceforge.net/),
1356     * but it's for linux only, and still not guaranteed.
1357     *
1358     * So for now, we just check that a valid Ecore_Exe structure
1359     * exists for it.  Even that is not a guarantee, as the structure
1360     * can be freed without killing the process.
1361     *
1362     * I think we can safely put exe's into two categories, those users
1363     * that care about the life of the exe, and the run and forget type.
1364     * The run and forget type starts up the exe, then free's the
1365     * Ecore_Exe structure straight away.  They can never call any of
1366     * the functions that can call this, so we don't worry about them.
1367     *
1368     * Those user's that care about the life of exe's will keep the
1369     * Ecore_Exe structure around, terminate them eventually, or
1370     * register for exit events.  For these ones the assumption
1371     * that valid Ecore_Exe struct == live exe is almost valid.
1372     *
1373     * I will probably copy my urunlevel code into here someday.
1374     */
1375    exe = _ecore_exe_find(pid);
1376    if (exe)
1377      {
1378         if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1379            exe = NULL;
1380      }
1381
1382    return exe;
1383 }
1384
1385 static int
1386 _ecore_exe_make_sure_its_dead(void *data)
1387 {
1388    struct _ecore_exe_dead_exe *dead;
1389
1390    dead = data;
1391    if (dead)
1392      {
1393         Ecore_Exe *exe = NULL;
1394
1395         if ((exe = _ecore_exe_is_it_alive(dead->pid)) != NULL)
1396           {
1397              if (dead->cmd)
1398                 INF("Sending KILL signal to alledgedly dead %s (%d).",
1399                        dead->cmd, dead->pid);
1400              else
1401                 INF("Sending KILL signal to alledgedly dead PID %d.",
1402                     dead->pid);
1403              exe->doomsday_clock =
1404                 ecore_timer_add(10.0, _ecore_exe_make_sure_its_really_dead,
1405                                 dead);
1406              kill(dead->pid, SIGKILL);
1407           }
1408         else
1409           {
1410              IF_FREE(dead->cmd);
1411              free(dead);
1412           }
1413      }
1414    return 0;
1415 }
1416
1417 static int
1418 _ecore_exe_make_sure_its_really_dead(void *data)
1419 {
1420    struct _ecore_exe_dead_exe *dead;
1421
1422    dead = data;
1423    if (dead)
1424      {
1425         Ecore_Exe *exe = NULL;
1426
1427         if ((exe = _ecore_exe_is_it_alive(dead->pid)) != NULL)
1428           {
1429              ERR("RUN!  The zombie wants to eat your brains!  And your CPU!");
1430              if (dead->cmd)
1431                 INF("%s (%d) is not really dead.", dead->cmd, dead->pid);
1432              else
1433                 INF("PID %d is not really dead.", dead->pid);
1434              exe->doomsday_clock = NULL;
1435           }
1436         IF_FREE(dead->cmd);
1437         free(dead);
1438      }
1439    return 0;
1440 }
1441
1442 void
1443 _ecore_exe_init(void)
1444 {
1445    ECORE_EXE_EVENT_ADD = ecore_event_type_new();
1446    ECORE_EXE_EVENT_DEL = ecore_event_type_new();
1447    ECORE_EXE_EVENT_DATA = ecore_event_type_new();
1448    ECORE_EXE_EVENT_ERROR = ecore_event_type_new();
1449 }
1450
1451 void
1452 _ecore_exe_shutdown(void)
1453 {
1454    while (exes)
1455      ecore_exe_free(exes);
1456 }
1457
1458 Ecore_Exe *
1459 _ecore_exe_find(pid_t pid)
1460 {
1461    Ecore_Exe *exe;
1462
1463    EINA_INLIST_FOREACH(exes, exe)
1464      {
1465         if (exe->pid == pid)
1466            return exe;
1467      }
1468    return NULL;
1469 }
1470
1471 Ecore_Timer *
1472 _ecore_exe_doomsday_clock_get(Ecore_Exe *exe)
1473 {
1474    return exe->doomsday_clock;
1475 }
1476
1477 void
1478 _ecore_exe_doomsday_clock_set(Ecore_Exe *exe, Ecore_Timer *dc)
1479 {
1480    exe->doomsday_clock = dc;
1481 }
1482
1483 static inline void
1484 _ecore_exe_exec_it(const char *exe_cmd, Ecore_Exe_Flags flags)
1485 {
1486    char use_sh = 1;
1487    char *buf = NULL;
1488    char **args = NULL;
1489    int  save_errno = 0;
1490
1491    /* So what is this doing?
1492     *
1493     * We are trying to avoid wrapping the exe call with /bin/sh -c.
1494     * We conservatively search for certain shell meta characters,
1495     * If we don't find them, we can call the exe directly.
1496     */
1497    if (!strpbrk(exe_cmd, "|&;<>()$`\\\"'*?#"))
1498      {
1499         char *token;
1500         char pre_command = 1;
1501         int num_tokens = 0;
1502
1503         if (!(buf = strdup(exe_cmd)))
1504            return;
1505
1506         token = strtok(buf, " \t\n\v");
1507         while (token)
1508           {
1509              if (token[0] == '~')
1510                break;
1511              if (pre_command)
1512                {
1513                   if (token[0] == '[')
1514                     break;
1515                   if (strchr(token, '='))
1516                     break;
1517                   else
1518                     pre_command = 0;
1519                }
1520              num_tokens++;
1521              token = strtok(NULL, " \t\n\v");
1522           }
1523         IF_FREE(buf);
1524         if ((!token) && (num_tokens))
1525           {
1526              int i = 0;
1527
1528              if (!(buf = strdup(exe_cmd)))
1529                return;
1530
1531              token = strtok(buf, " \t\n\v");
1532              use_sh = 0;
1533              if (!(args = (char **)calloc(num_tokens + 1, sizeof(char *))))
1534                {
1535                   IF_FREE(buf);
1536                   return;
1537                }
1538              for (i = 0; i < num_tokens; i++)
1539                {
1540                   if (token)
1541                     args[i] = token;
1542                   token = strtok(NULL, " \t\n\v");
1543                }
1544              args[num_tokens] = NULL;
1545           }
1546      }
1547
1548    if (!(flags & ECORE_EXE_NOT_LEADER)) setsid();
1549    if ((flags & ECORE_EXE_USE_SH))
1550      {
1551         errno = 0;
1552         execl("/bin/sh", "/bin/sh", "-c", exe_cmd, (char *)NULL);
1553      }
1554    else if (use_sh)
1555      {                          /* We have to use a shell to run this. */
1556         if (shell == NULL)
1557           {                     /* Find users preferred shell. */
1558              shell = getenv("SHELL");
1559              if (shell == 0)
1560                shell = "/bin/sh";
1561           }
1562         errno = 0;
1563         execl(shell, shell, "-c", exe_cmd, (char *)NULL);
1564      }
1565    else
1566      {                          /* We can run this directly. */
1567         errno = 0;
1568         execvp(args[0], args);
1569      }
1570
1571    save_errno = errno;
1572    IF_FREE(buf);
1573    IF_FREE(args);
1574    errno = save_errno;
1575    return;
1576 }
1577
1578 static int
1579 _ecore_exe_data_generic_handler(void *data, Ecore_Fd_Handler *fd_handler, Ecore_Exe_Flags flags)
1580 {
1581    Ecore_Exe *exe;
1582    int child_fd;
1583    int event_type;
1584
1585    exe = data;
1586
1587    /* Sort out what sort of handler we are. */
1588    if (flags & ECORE_EXE_PIPE_READ)
1589      {
1590         flags = ECORE_EXE_PIPE_READ;
1591         event_type = ECORE_EXE_EVENT_DATA;
1592         child_fd = exe->child_fd_read;
1593      }
1594    else
1595      {
1596         flags = ECORE_EXE_PIPE_ERROR;
1597         event_type = ECORE_EXE_EVENT_ERROR;
1598         child_fd = exe->child_fd_error;
1599      }
1600
1601    if ((fd_handler)
1602        && (ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ)))
1603      {
1604         unsigned char *inbuf;
1605         int inbuf_num;
1606
1607         /* Get any left over data from last time. */
1608         if (flags & ECORE_EXE_PIPE_READ)
1609           {
1610              inbuf = exe->read_data_buf;
1611              inbuf_num = exe->read_data_size;
1612              exe->read_data_buf = NULL;
1613              exe->read_data_size = 0;
1614           }
1615         else
1616           {
1617              inbuf = exe->error_data_buf;
1618              inbuf_num = exe->error_data_size;
1619              exe->error_data_buf = NULL;
1620              exe->error_data_size = 0;
1621           }
1622
1623         for (;;)
1624           {
1625              int num, lost_exe;
1626              char buf[READBUFSIZ];
1627
1628              lost_exe = 0;
1629              errno = 0;
1630              if ((num = read(child_fd, buf, READBUFSIZ)) < 1)
1631                /* FIXME: SPEED/SIZE TRADE OFF - add a smaller READBUFSIZE
1632                 * (currently 64k) to inbuf, use that instead of buf, and
1633                 * save ourselves a memcpy(). */
1634                {
1635                   lost_exe = ((errno == EIO) ||
1636                               (errno == EBADF) ||
1637                               (errno == EPIPE) ||
1638                               (errno == EINVAL) || (errno == ENOSPC));
1639                   if ((errno != EAGAIN) && (errno != EINTR))
1640                      perror("_ecore_exe_generic_handler() read problem ");
1641                }
1642              if (num > 0)
1643                {                /* data got read. */
1644                   inbuf = realloc(inbuf, inbuf_num + num);
1645                   memcpy(inbuf + inbuf_num, buf, num);
1646                   inbuf_num += num;
1647                }
1648              else
1649                {                /* No more data to read. */
1650                   if (inbuf)
1651                     {
1652                        Ecore_Exe_Event_Data *e;
1653
1654                        /* Stash the data away for later. */
1655                        if (flags & ECORE_EXE_PIPE_READ)
1656                          {
1657                             exe->read_data_buf = inbuf;
1658                             exe->read_data_size = inbuf_num;
1659                          }
1660                        else
1661                          {
1662                             exe->error_data_buf = inbuf;
1663                             exe->error_data_size = inbuf_num;
1664                          }
1665
1666                        if (!(exe->flags & ECORE_EXE_PIPE_AUTO))
1667                          {
1668                             e = ecore_exe_event_data_get(exe, flags);
1669                             if (e)      /* Send the event. */
1670                               ecore_event_add(event_type, e,
1671                                               _ecore_exe_event_exe_data_free,
1672                                               NULL);
1673                          }
1674                     }
1675                   if (lost_exe)
1676                     {
1677                        if (flags & ECORE_EXE_PIPE_READ)
1678                          {
1679                             if (exe->read_data_size)
1680                               INF("There are %d bytes left unsent from the dead exe %s.",
1681                                   exe->read_data_size, exe->cmd);
1682                          }
1683                        else
1684                          {
1685                             if (exe->error_data_size)
1686                               INF("There are %d bytes left unsent from the dead exe %s.",
1687                                   exe->error_data_size, exe->cmd);
1688                          }
1689                        /* Thought about this a bit.  If the exe has actually
1690                         * died, this won't do any harm as it must have died
1691                         * recently and the pid has not had a chance to recycle.
1692                         * It is also a paranoid catchall, coz the usual ecore_signal
1693                         * mechenism should kick in.  But let's give it a good
1694                         * kick in the head anyway.
1695                         */
1696                        ecore_exe_terminate(exe);
1697                     }
1698                   break;
1699                }
1700           }
1701      }
1702
1703    return 1;
1704 }
1705
1706 static int
1707 _ecore_exe_data_error_handler(void *data, Ecore_Fd_Handler *fd_handler)
1708 {
1709    return _ecore_exe_data_generic_handler(data, fd_handler,
1710                                           ECORE_EXE_PIPE_ERROR);
1711 }
1712
1713 static int
1714 _ecore_exe_data_read_handler(void *data, Ecore_Fd_Handler *fd_handler)
1715 {
1716    return _ecore_exe_data_generic_handler(data, fd_handler,
1717                                           ECORE_EXE_PIPE_READ);
1718 }
1719
1720 static int
1721 _ecore_exe_data_write_handler(void *data, Ecore_Fd_Handler *fd_handler __UNUSED__)
1722 {
1723    Ecore_Exe *exe;
1724
1725    exe = data;
1726    if ((exe->write_fd_handler) &&
1727        (ecore_main_fd_handler_active_get
1728         (exe->write_fd_handler, ECORE_FD_WRITE)))
1729      _ecore_exe_flush(exe);
1730
1731    /* If we have sent all there is to send, and we need to close the pipe, then close it. */
1732    if ((exe->close_stdin == 1)
1733        && (exe->write_data_size == exe->write_data_offset))
1734      {
1735         int ok = 0;
1736         int result;
1737
1738         INF("Closing stdin for %s", exe->cmd);
1739         /* if (exe->child_fd_write != -1)  E_NO_ERRNO(result, fsync(exe->child_fd_write), ok);   This a) doesn't work, and b) isn't needed. */
1740         IF_FN_DEL(ecore_main_fd_handler_del, exe->write_fd_handler);
1741         if (exe->child_fd_write != -1)
1742            E_NO_ERRNO(result, close(exe->child_fd_write), ok);
1743         exe->child_fd_write = -1;
1744         IF_FREE(exe->write_data_buf);
1745      }
1746
1747    return 1;
1748 }
1749
1750 static void
1751 _ecore_exe_flush(Ecore_Exe *exe)
1752 {
1753    int count;
1754
1755    /* check whether we need to write anything at all. */
1756    if ((exe->child_fd_write == -1) || (!exe->write_data_buf))
1757       return;
1758    if (exe->write_data_size == exe->write_data_offset)
1759       return;
1760
1761    count = write(exe->child_fd_write,
1762                  (char *)exe->write_data_buf + exe->write_data_offset,
1763                  exe->write_data_size - exe->write_data_offset);
1764    if (count < 1)
1765      {
1766         if (errno == EIO || errno == EBADF || errno == EPIPE || errno == EINVAL || errno == ENOSPC)     /* we lost our exe! */
1767           {
1768              ecore_exe_terminate(exe);
1769              if (exe->write_fd_handler)
1770                 ecore_main_fd_handler_active_set(exe->write_fd_handler, 0);
1771           }
1772      }
1773    else
1774      {
1775         exe->write_data_offset += count;
1776         if (exe->write_data_offset >= exe->write_data_size)
1777           {                     /* Nothing left to write, clean up. */
1778              exe->write_data_size = 0;
1779              exe->write_data_offset = 0;
1780              IF_FREE(exe->write_data_buf);
1781              if (exe->write_fd_handler)
1782                 ecore_main_fd_handler_active_set(exe->write_fd_handler, 0);
1783           }
1784      }
1785 }
1786
1787 static void
1788 _ecore_exe_event_exe_data_free(void *data __UNUSED__, void *ev)
1789 {
1790    Ecore_Exe_Event_Data *e;
1791
1792    e = ev;
1793    ecore_exe_event_data_free(e);
1794 }
1795
1796 static Ecore_Exe_Event_Add *
1797 _ecore_exe_event_add_new(void)
1798 {
1799    Ecore_Exe_Event_Add *e;
1800
1801    e = calloc(1, sizeof(Ecore_Exe_Event_Add));
1802    return e;
1803 }
1804
1805 static void
1806 _ecore_exe_event_add_free(void *data __UNUSED__, void *ev)
1807 {
1808    Ecore_Exe_Event_Add *e;
1809
1810    e = ev;
1811    free(e);
1812 }
1813
1814 void               *
1815 _ecore_exe_event_del_new(void)
1816 {
1817    Ecore_Exe_Event_Del *e;
1818
1819    e = calloc(1, sizeof(Ecore_Exe_Event_Del));
1820    return e;
1821 }
1822
1823 void
1824 _ecore_exe_event_del_free(void *data __UNUSED__, void *ev)
1825 {
1826    Ecore_Exe_Event_Del *e;
1827
1828    e = ev;
1829    if (e->exe)
1830      ecore_exe_free(e->exe);
1831    free(e);
1832 }
1833
1834 static void
1835 _ecore_exe_dead_attach(Ecore_Exe *exe)
1836 {
1837    struct _ecore_exe_dead_exe *dead;
1838
1839    if (exe->doomsday_clock_dead) return;
1840    dead = calloc(1, sizeof(struct _ecore_exe_dead_exe));
1841    if (dead)
1842      {
1843         dead->pid = exe->pid;
1844         dead->cmd = strdup(exe->cmd);
1845         IF_FN_DEL(ecore_timer_del, exe->doomsday_clock);
1846         exe->doomsday_clock =
1847            ecore_timer_add(10.0, _ecore_exe_make_sure_its_dead, dead);
1848         exe->doomsday_clock_dead = dead;
1849      }
1850 }