Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Source / kwsys / ProcessUNIX.c
blobbf1cd8320ab9abed65be99b88fa4effe6db04a09
1 /*=========================================================================
3 Program: KWSys - Kitware System Library
4 Module: $RCSfile: ProcessUNIX.c,v $
6 Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
7 See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
9 This software is distributed WITHOUT ANY WARRANTY; without even
10 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11 PURPOSE. See the above copyright notices for more information.
13 =========================================================================*/
14 #include "kwsysPrivate.h"
15 #include KWSYS_HEADER(Process.h)
17 /* Work-around CMake dependency scanning limitation. This must
18 duplicate the above list of headers. */
19 #if 0
20 # include "Process.h.in"
21 #endif
25 Implementation for UNIX
27 On UNIX, a child process is forked to exec the program. Three output
28 pipes are read by the parent process using a select call to block
29 until data are ready. Two of the pipes are stdout and stderr for the
30 child. The third is a special pipe populated by a signal handler to
31 indicate that a child has terminated. This is used in conjunction
32 with the timeout on the select call to implement a timeout for program
33 even when it closes stdout and stderr and at the same time avoiding
34 races.
41 TODO:
43 We cannot create the pipeline of processes in suspended states. How
44 do we cleanup processes already started when one fails to load? Right
45 now we are just killing them, which is probably not the right thing to
46 do.
50 #include <stddef.h> /* ptrdiff_t */
51 #include <stdio.h> /* snprintf */
52 #include <stdlib.h> /* malloc, free */
53 #include <string.h> /* strdup, strerror, memset */
54 #include <sys/time.h> /* struct timeval */
55 #include <sys/types.h> /* pid_t, fd_set */
56 #include <sys/wait.h> /* waitpid */
57 #include <sys/stat.h> /* open mode */
58 #include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
59 #include <fcntl.h> /* fcntl */
60 #include <errno.h> /* errno */
61 #include <time.h> /* gettimeofday */
62 #include <signal.h> /* sigaction */
63 #include <dirent.h> /* DIR, dirent */
64 #include <ctype.h> /* isspace */
66 #ifdef __HAIKU__
67 #undef __BEOS__
68 #endif
70 #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
71 typedef ptrdiff_t kwsysProcess_ptrdiff_t;
72 #else
73 typedef int kwsysProcess_ptrdiff_t;
74 #endif
76 #if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
77 typedef ssize_t kwsysProcess_ssize_t;
78 #else
79 typedef int kwsysProcess_ssize_t;
80 #endif
82 #if defined(__BEOS__) && !defined(__ZETA__)
83 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
84 # include <be/kernel/OS.h>
85 static inline void kwsysProcess_usleep(unsigned int msec)
87 snooze(msec);
89 #else
90 # define kwsysProcess_usleep usleep
91 #endif
94 * BeOS's select() works like WinSock: it's for networking only, and
95 * doesn't work with Unix file handles...socket and file handles are
96 * different namespaces (the same descriptor means different things in
97 * each context!)
99 * So on Unix-like systems where select() is flakey, we'll set the
100 * pipes' file handles to be non-blocking and just poll them directly
101 * without select().
103 #if !defined(__BEOS__)
104 # define KWSYSPE_USE_SELECT 1
105 #endif
107 /* Some platforms do not have siginfo on their signal handlers. */
108 #if defined(SA_SIGINFO) && !defined(__BEOS__)
109 # define KWSYSPE_USE_SIGINFO 1
110 #endif
112 /* The number of pipes for the child's output. The standard stdout
113 and stderr pipes are the first two. One more pipe is used to
114 detect when the child process has terminated. The third pipe is
115 not given to the child process, so it cannot close it until it
116 terminates. */
117 #define KWSYSPE_PIPE_COUNT 3
118 #define KWSYSPE_PIPE_STDOUT 0
119 #define KWSYSPE_PIPE_STDERR 1
120 #define KWSYSPE_PIPE_SIGNAL 2
122 /* The maximum amount to read from a pipe at a time. */
123 #define KWSYSPE_PIPE_BUFFER_SIZE 1024
125 /* Keep track of times using a signed representation. Switch to the
126 native (possibly unsigned) representation only when calling native
127 functions. */
128 typedef struct timeval kwsysProcessTimeNative;
129 typedef struct kwsysProcessTime_s kwsysProcessTime;
130 struct kwsysProcessTime_s
132 long tv_sec;
133 long tv_usec;
136 typedef struct kwsysProcessCreateInformation_s
138 int StdIn;
139 int StdOut;
140 int StdErr;
141 int ErrorPipe[2];
142 } kwsysProcessCreateInformation;
144 /*--------------------------------------------------------------------------*/
145 static int kwsysProcessInitialize(kwsysProcess* cp);
146 static void kwsysProcessCleanup(kwsysProcess* cp, int error);
147 static void kwsysProcessCleanupDescriptor(int* pfd);
148 static void kwsysProcessClosePipes(kwsysProcess* cp);
149 static int kwsysProcessSetNonBlocking(int fd);
150 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
151 kwsysProcessCreateInformation* si, int* readEnd);
152 static void kwsysProcessDestroy(kwsysProcess* cp);
153 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
154 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]);
155 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
156 kwsysProcessTime* timeoutTime);
157 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
158 double* userTimeout,
159 kwsysProcessTimeNative* timeoutLength);
160 static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
161 static double kwsysProcessTimeToDouble(kwsysProcessTime t);
162 static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
163 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
164 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
165 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
166 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
167 static void kwsysProcessChildErrorExit(int errorPipe);
168 static void kwsysProcessRestoreDefaultSignalHandlers(void);
169 static pid_t kwsysProcessFork(kwsysProcess* cp,
170 kwsysProcessCreateInformation* si);
171 static void kwsysProcessKill(pid_t process_id);
172 static int kwsysProcessesAdd(kwsysProcess* cp);
173 static void kwsysProcessesRemove(kwsysProcess* cp);
174 #if KWSYSPE_USE_SIGINFO
175 static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
176 void* ucontext);
177 #else
178 static void kwsysProcessesSignalHandler(int signum);
179 #endif
180 static char** kwsysProcessParseVerbatimCommand(const char* command);
182 /*--------------------------------------------------------------------------*/
183 /* Structure containing data used to implement the child's execution. */
184 struct kwsysProcess_s
186 /* The command lines to execute. */
187 char*** Commands;
188 int NumberOfCommands;
190 /* Descriptors for the read ends of the child's output pipes and
191 the signal pipe. */
192 int PipeReadEnds[KWSYSPE_PIPE_COUNT];
194 /* Write descriptor for child termination signal pipe. */
195 int SignalPipe;
197 /* Buffer for pipe data. */
198 char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
200 /* Process IDs returned by the calls to fork. */
201 pid_t* ForkPIDs;
203 /* Flag for whether the children were terminated by a faild select. */
204 int SelectError;
206 /* The timeout length. */
207 double Timeout;
209 /* The working directory for the process. */
210 char* WorkingDirectory;
212 /* Whether to create the child as a detached process. */
213 int OptionDetach;
215 /* Whether the child was created as a detached process. */
216 int Detached;
218 /* Whether to treat command lines as verbatim. */
219 int Verbatim;
221 /* Time at which the child started. Negative for no timeout. */
222 kwsysProcessTime StartTime;
224 /* Time at which the child will timeout. Negative for no timeout. */
225 kwsysProcessTime TimeoutTime;
227 /* Flag for whether the timeout expired. */
228 int TimeoutExpired;
230 /* The number of pipes left open during execution. */
231 int PipesLeft;
233 #if KWSYSPE_USE_SELECT
234 /* File descriptor set for call to select. */
235 fd_set PipeSet;
236 #endif
238 /* The number of children still executing. */
239 int CommandsLeft;
241 /* The current status of the child process. */
242 int State;
244 /* The exceptional behavior that terminated the child process, if
245 * any. */
246 int ExitException;
248 /* The exit code of the child process. */
249 int ExitCode;
251 /* The exit value of the child process, if any. */
252 int ExitValue;
254 /* Whether the process was killed. */
255 int Killed;
257 /* Buffer for error message in case of failure. */
258 char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
260 /* Description for the ExitException. */
261 char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
263 /* The exit codes of each child process in the pipeline. */
264 int* CommandExitCodes;
266 /* Name of files to which stdin and stdout pipes are attached. */
267 char* PipeFileSTDIN;
268 char* PipeFileSTDOUT;
269 char* PipeFileSTDERR;
271 /* Whether each pipe is shared with the parent process. */
272 int PipeSharedSTDIN;
273 int PipeSharedSTDOUT;
274 int PipeSharedSTDERR;
276 /* Native pipes provided by the user. */
277 int PipeNativeSTDIN[2];
278 int PipeNativeSTDOUT[2];
279 int PipeNativeSTDERR[2];
281 /* The real working directory of this process. */
282 int RealWorkingDirectoryLength;
283 char* RealWorkingDirectory;
286 /*--------------------------------------------------------------------------*/
287 kwsysProcess* kwsysProcess_New(void)
289 /* Allocate a process control structure. */
290 kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
291 if(!cp)
293 return 0;
295 memset(cp, 0, sizeof(kwsysProcess));
297 /* Share stdin with the parent process by default. */
298 cp->PipeSharedSTDIN = 1;
300 /* No native pipes by default. */
301 cp->PipeNativeSTDIN[0] = -1;
302 cp->PipeNativeSTDIN[1] = -1;
303 cp->PipeNativeSTDOUT[0] = -1;
304 cp->PipeNativeSTDOUT[1] = -1;
305 cp->PipeNativeSTDERR[0] = -1;
306 cp->PipeNativeSTDERR[1] = -1;
308 /* Set initial status. */
309 cp->State = kwsysProcess_State_Starting;
311 return cp;
314 /*--------------------------------------------------------------------------*/
315 void kwsysProcess_Delete(kwsysProcess* cp)
317 /* Make sure we have an instance. */
318 if(!cp)
320 return;
323 /* If the process is executing, wait for it to finish. */
324 if(cp->State == kwsysProcess_State_Executing)
326 if(cp->Detached)
328 kwsysProcess_Disown(cp);
330 else
332 kwsysProcess_WaitForExit(cp, 0);
336 /* Free memory. */
337 kwsysProcess_SetCommand(cp, 0);
338 kwsysProcess_SetWorkingDirectory(cp, 0);
339 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
340 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
341 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
342 if(cp->CommandExitCodes)
344 free(cp->CommandExitCodes);
346 free(cp);
349 /*--------------------------------------------------------------------------*/
350 int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
352 int i;
353 if(!cp)
355 return 0;
357 for(i=0; i < cp->NumberOfCommands; ++i)
359 char** c = cp->Commands[i];
360 while(*c)
362 free(*c++);
364 free(cp->Commands[i]);
366 cp->NumberOfCommands = 0;
367 if(cp->Commands)
369 free(cp->Commands);
370 cp->Commands = 0;
372 if(command)
374 return kwsysProcess_AddCommand(cp, command);
376 return 1;
379 /*--------------------------------------------------------------------------*/
380 int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
382 int newNumberOfCommands;
383 char*** newCommands;
385 /* Make sure we have a command to add. */
386 if(!cp || !command || !*command)
388 return 0;
391 /* Allocate a new array for command pointers. */
392 newNumberOfCommands = cp->NumberOfCommands + 1;
393 if(!(newCommands =
394 (char***)malloc(sizeof(char**) *(size_t)(newNumberOfCommands))))
396 /* Out of memory. */
397 return 0;
400 /* Copy any existing commands into the new array. */
402 int i;
403 for(i=0; i < cp->NumberOfCommands; ++i)
405 newCommands[i] = cp->Commands[i];
409 /* Add the new command. */
410 if(cp->Verbatim)
412 /* In order to run the given command line verbatim we need to
413 parse it. */
414 newCommands[cp->NumberOfCommands] =
415 kwsysProcessParseVerbatimCommand(*command);
416 if(!newCommands[cp->NumberOfCommands])
418 /* Out of memory. */
419 free(newCommands);
420 return 0;
423 else
425 /* Copy each argument string individually. */
426 char const* const* c = command;
427 kwsysProcess_ptrdiff_t n = 0;
428 kwsysProcess_ptrdiff_t i = 0;
429 while(*c++);
430 n = c - command - 1;
431 newCommands[cp->NumberOfCommands] =
432 (char**)malloc((size_t)(n+1)*sizeof(char*));
433 if(!newCommands[cp->NumberOfCommands])
435 /* Out of memory. */
436 free(newCommands);
437 return 0;
439 for(i=0; i < n; ++i)
441 newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
442 if(!newCommands[cp->NumberOfCommands][i])
444 break;
447 if(i < n)
449 /* Out of memory. */
450 for(;i > 0; --i)
452 free(newCommands[cp->NumberOfCommands][i-1]);
454 free(newCommands);
455 return 0;
457 newCommands[cp->NumberOfCommands][n] = 0;
460 /* Successfully allocated new command array. Free the old array. */
461 free(cp->Commands);
462 cp->Commands = newCommands;
463 cp->NumberOfCommands = newNumberOfCommands;
465 return 1;
468 /*--------------------------------------------------------------------------*/
469 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
471 if(!cp)
473 return;
475 cp->Timeout = timeout;
476 if(cp->Timeout < 0)
478 cp->Timeout = 0;
482 /*--------------------------------------------------------------------------*/
483 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
485 if(!cp)
487 return 0;
489 if(cp->WorkingDirectory == dir)
491 return 1;
493 if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
495 return 1;
497 if(cp->WorkingDirectory)
499 free(cp->WorkingDirectory);
500 cp->WorkingDirectory = 0;
502 if(dir)
504 cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
505 if(!cp->WorkingDirectory)
507 return 0;
509 strcpy(cp->WorkingDirectory, dir);
511 return 1;
514 /*--------------------------------------------------------------------------*/
515 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
517 char** pfile;
518 if(!cp)
520 return 0;
522 switch(prPipe)
524 case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
525 case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
526 case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
527 default: return 0;
529 if(*pfile)
531 free(*pfile);
532 *pfile = 0;
534 if(file)
536 *pfile = malloc(strlen(file)+1);
537 if(!*pfile)
539 return 0;
541 strcpy(*pfile, file);
544 /* If we are redirecting the pipe, do not share it or use a native
545 pipe. */
546 if(*pfile)
548 kwsysProcess_SetPipeNative(cp, prPipe, 0);
549 kwsysProcess_SetPipeShared(cp, prPipe, 0);
551 return 1;
554 /*--------------------------------------------------------------------------*/
555 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
557 if(!cp)
559 return;
562 switch(prPipe)
564 case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
565 case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
566 case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
567 default: return;
570 /* If we are sharing the pipe, do not redirect it to a file or use a
571 native pipe. */
572 if(shared)
574 kwsysProcess_SetPipeFile(cp, prPipe, 0);
575 kwsysProcess_SetPipeNative(cp, prPipe, 0);
579 /*--------------------------------------------------------------------------*/
580 void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
582 int* pPipeNative = 0;
584 if(!cp)
586 return;
589 switch(prPipe)
591 case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
592 case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
593 case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
594 default: return;
597 /* Copy the native pipe descriptors provided. */
598 if(p)
600 pPipeNative[0] = p[0];
601 pPipeNative[1] = p[1];
603 else
605 pPipeNative[0] = -1;
606 pPipeNative[1] = -1;
609 /* If we are using a native pipe, do not share it or redirect it to
610 a file. */
611 if(p)
613 kwsysProcess_SetPipeFile(cp, prPipe, 0);
614 kwsysProcess_SetPipeShared(cp, prPipe, 0);
618 /*--------------------------------------------------------------------------*/
619 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
621 if(!cp)
623 return 0;
626 switch(optionId)
628 case kwsysProcess_Option_Detach: return cp->OptionDetach;
629 case kwsysProcess_Option_Verbatim: return cp->Verbatim;
630 default: return 0;
634 /*--------------------------------------------------------------------------*/
635 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
637 if(!cp)
639 return;
642 switch(optionId)
644 case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
645 case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
646 default: break;
650 /*--------------------------------------------------------------------------*/
651 int kwsysProcess_GetState(kwsysProcess* cp)
653 return cp? cp->State : kwsysProcess_State_Error;
656 /*--------------------------------------------------------------------------*/
657 int kwsysProcess_GetExitException(kwsysProcess* cp)
659 return cp? cp->ExitException : kwsysProcess_Exception_Other;
662 /*--------------------------------------------------------------------------*/
663 int kwsysProcess_GetExitCode(kwsysProcess* cp)
665 return cp? cp->ExitCode : 0;
668 /*--------------------------------------------------------------------------*/
669 int kwsysProcess_GetExitValue(kwsysProcess* cp)
671 return cp? cp->ExitValue : -1;
674 /*--------------------------------------------------------------------------*/
675 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
677 if(!cp)
679 return "Process management structure could not be allocated";
681 else if(cp->State == kwsysProcess_State_Error)
683 return cp->ErrorMessage;
685 return "Success";
688 /*--------------------------------------------------------------------------*/
689 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
691 if(!cp)
693 return "GetExceptionString called with NULL process management structure";
695 else if(cp->State == kwsysProcess_State_Exception)
697 return cp->ExitExceptionString;
699 return "No exception";
702 /*--------------------------------------------------------------------------*/
703 void kwsysProcess_Execute(kwsysProcess* cp)
705 int i;
706 kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
708 /* Do not execute a second copy simultaneously. */
709 if(!cp || cp->State == kwsysProcess_State_Executing)
711 return;
714 /* Initialize the control structure for a new process. */
715 if(!kwsysProcessInitialize(cp))
717 strcpy(cp->ErrorMessage, "Out of memory");
718 cp->State = kwsysProcess_State_Error;
719 return;
722 /* Save the real working directory of this process and change to
723 the working directory for the child processes. This is needed
724 to make pipe file paths evaluate correctly. */
725 if(cp->WorkingDirectory)
727 int r;
728 if(!getcwd(cp->RealWorkingDirectory,
729 (size_t)(cp->RealWorkingDirectoryLength)))
731 kwsysProcessCleanup(cp, 1);
732 return;
735 /* Some platforms specify that the chdir call may be
736 interrupted. Repeat the call until it finishes. */
737 while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
738 if(r < 0)
740 kwsysProcessCleanup(cp, 1);
741 return;
745 /* If not running a detached child, add this object to the global
746 set of process objects that wish to be notified when a child
747 exits. */
748 if(!cp->OptionDetach)
750 if(!kwsysProcessesAdd(cp))
752 kwsysProcessCleanup(cp, 1);
753 return;
757 /* Setup the stderr pipe to be shared by all processes. */
759 /* Create the pipe. */
760 int p[2];
761 if(pipe(p) < 0)
763 kwsysProcessCleanup(cp, 1);
764 return;
767 /* Store the pipe. */
768 cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
769 si.StdErr = p[1];
771 /* Set close-on-exec flag on the pipe's ends. */
772 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
773 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
775 kwsysProcessCleanup(cp, 1);
776 kwsysProcessCleanupDescriptor(&si.StdErr);
777 return;
780 /* Set to non-blocking in case select lies, or for the polling
781 implementation. */
782 if(!kwsysProcessSetNonBlocking(p[0]))
784 kwsysProcessCleanup(cp, 1);
785 kwsysProcessCleanupDescriptor(&si.StdErr);
786 return;
790 /* Replace the stderr pipe with a file if requested. In this case
791 the select call will report that stderr is closed immediately. */
792 if(cp->PipeFileSTDERR)
794 if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
796 kwsysProcessCleanup(cp, 1);
797 kwsysProcessCleanupDescriptor(&si.StdErr);
798 return;
802 /* Replace the stderr pipe with the parent's if requested. In this
803 case the select call will report that stderr is closed
804 immediately. */
805 if(cp->PipeSharedSTDERR)
807 kwsysProcessCleanupDescriptor(&si.StdErr);
808 si.StdErr = 2;
811 /* Replace the stderr pipe with the native pipe provided if any. In
812 this case the select call will report that stderr is closed
813 immediately. */
814 if(cp->PipeNativeSTDERR[1] >= 0)
816 if(!kwsysProcessSetupOutputPipeNative(&si.StdErr, cp->PipeNativeSTDERR))
818 kwsysProcessCleanup(cp, 1);
819 kwsysProcessCleanupDescriptor(&si.StdErr);
820 return;
824 /* The timeout period starts now. */
825 cp->StartTime = kwsysProcessTimeGetCurrent();
826 cp->TimeoutTime.tv_sec = -1;
827 cp->TimeoutTime.tv_usec = -1;
829 /* Create the pipeline of processes. */
831 int readEnd = -1;
832 int failed = 0;
833 for(i=0; i < cp->NumberOfCommands; ++i)
835 if(!kwsysProcessCreate(cp, i, &si, &readEnd))
837 failed = 1;
840 /* Set the output pipe of the last process to be non-blocking in
841 case select lies, or for the polling implementation. */
842 if(i == (cp->NumberOfCommands-1) && !kwsysProcessSetNonBlocking(readEnd))
844 failed = 1;
847 if(failed)
849 kwsysProcessCleanup(cp, 1);
851 /* Release resources that may have been allocated for this
852 process before an error occurred. */
853 kwsysProcessCleanupDescriptor(&readEnd);
854 if(si.StdIn != 0)
856 kwsysProcessCleanupDescriptor(&si.StdIn);
858 if(si.StdOut != 1)
860 kwsysProcessCleanupDescriptor(&si.StdOut);
862 if(si.StdErr != 2)
864 kwsysProcessCleanupDescriptor(&si.StdErr);
866 kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
867 kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
868 return;
871 /* Save a handle to the output pipe for the last process. */
872 cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
875 /* The parent process does not need the output pipe write ends. */
876 if(si.StdErr != 2)
878 kwsysProcessCleanupDescriptor(&si.StdErr);
881 /* Restore the working directory. */
882 if(cp->RealWorkingDirectory)
884 /* Some platforms specify that the chdir call may be
885 interrupted. Repeat the call until it finishes. */
886 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
887 free(cp->RealWorkingDirectory);
888 cp->RealWorkingDirectory = 0;
891 /* All the pipes are now open. */
892 cp->PipesLeft = KWSYSPE_PIPE_COUNT;
894 /* The process has now started. */
895 cp->State = kwsysProcess_State_Executing;
896 cp->Detached = cp->OptionDetach;
899 /*--------------------------------------------------------------------------*/
900 kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
902 /* Make sure a detached child process is running. */
903 if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
904 cp->TimeoutExpired || cp->Killed)
906 return;
909 /* Close all the pipes safely. */
910 kwsysProcessClosePipes(cp);
912 /* We will not wait for exit, so cleanup now. */
913 kwsysProcessCleanup(cp, 0);
915 /* The process has been disowned. */
916 cp->State = kwsysProcess_State_Disowned;
919 /*--------------------------------------------------------------------------*/
920 typedef struct kwsysProcessWaitData_s
922 int Expired;
923 int PipeId;
924 int User;
925 double* UserTimeout;
926 kwsysProcessTime TimeoutTime;
927 } kwsysProcessWaitData;
928 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
929 kwsysProcessWaitData* wd);
931 /*--------------------------------------------------------------------------*/
932 int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
933 double* userTimeout)
935 kwsysProcessTime userStartTime = {0, 0};
936 kwsysProcessWaitData wd =
939 kwsysProcess_Pipe_None,
942 {0, 0}
944 wd.UserTimeout = userTimeout;
945 /* Make sure we are executing a process. */
946 if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
947 cp->TimeoutExpired)
949 return kwsysProcess_Pipe_None;
952 /* Record the time at which user timeout period starts. */
953 if(userTimeout)
955 userStartTime = kwsysProcessTimeGetCurrent();
958 /* Calculate the time at which a timeout will expire, and whether it
959 is the user or process timeout. */
960 wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
961 &wd.TimeoutTime);
963 /* Data can only be available when pipes are open. If the process
964 is not running, cp->PipesLeft will be 0. */
965 while(cp->PipesLeft > 0 &&
966 !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
968 /* Update the user timeout. */
969 if(userTimeout)
971 kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
972 kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
973 userStartTime);
974 double d = kwsysProcessTimeToDouble(difference);
975 *userTimeout -= d;
976 if(*userTimeout < 0)
978 *userTimeout = 0;
982 /* Check what happened. */
983 if(wd.PipeId)
985 /* Data are ready on a pipe. */
986 return wd.PipeId;
988 else if(wd.Expired)
990 /* A timeout has expired. */
991 if(wd.User)
993 /* The user timeout has expired. It has no time left. */
994 return kwsysProcess_Pipe_Timeout;
996 else
998 /* The process timeout has expired. Kill the children now. */
999 kwsysProcess_Kill(cp);
1000 cp->Killed = 0;
1001 cp->TimeoutExpired = 1;
1002 return kwsysProcess_Pipe_None;
1005 else
1007 /* No pipes are left open. */
1008 return kwsysProcess_Pipe_None;
1012 /*--------------------------------------------------------------------------*/
1013 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
1014 kwsysProcessWaitData* wd)
1016 int i;
1017 kwsysProcessTimeNative timeoutLength;
1019 #if KWSYSPE_USE_SELECT
1020 int numReady = 0;
1021 int max = -1;
1022 kwsysProcessTimeNative* timeout = 0;
1024 /* Check for any open pipes with data reported ready by the last
1025 call to select. According to "man select_tut" we must deal
1026 with all descriptors reported by a call to select before
1027 passing them to another select call. */
1028 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1030 if(cp->PipeReadEnds[i] >= 0 &&
1031 FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1033 kwsysProcess_ssize_t n;
1035 /* We are handling this pipe now. Remove it from the set. */
1036 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1038 /* The pipe is ready to read without blocking. Keep trying to
1039 read until the operation is not interrupted. */
1040 while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
1041 KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
1042 if(n > 0)
1044 /* We have data on this pipe. */
1045 if(i == KWSYSPE_PIPE_SIGNAL)
1047 /* A child process has terminated. */
1048 kwsysProcessDestroy(cp);
1050 else if(data && length)
1052 /* Report this data. */
1053 *data = cp->PipeBuffer;
1054 *length = (int)(n);
1055 switch(i)
1057 case KWSYSPE_PIPE_STDOUT:
1058 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1059 case KWSYSPE_PIPE_STDERR:
1060 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1062 return 1;
1065 else if(n < 0 && errno == EAGAIN)
1067 /* No data are really ready. The select call lied. See the
1068 "man select" page on Linux for cases when this occurs. */
1070 else
1072 /* We are done reading from this pipe. */
1073 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1074 --cp->PipesLeft;
1079 /* If we have data, break early. */
1080 if(wd->PipeId)
1082 return 1;
1085 /* Make sure the set is empty (it should always be empty here
1086 anyway). */
1087 FD_ZERO(&cp->PipeSet);
1089 /* Setup a timeout if required. */
1090 if(wd->TimeoutTime.tv_sec < 0)
1092 timeout = 0;
1094 else
1096 timeout = &timeoutLength;
1098 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
1099 wd->User?wd->UserTimeout:0,
1100 &timeoutLength))
1102 /* Timeout has already expired. */
1103 wd->Expired = 1;
1104 return 1;
1107 /* Add the pipe reading ends that are still open. */
1108 max = -1;
1109 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1111 if(cp->PipeReadEnds[i] >= 0)
1113 FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
1114 if(cp->PipeReadEnds[i] > max)
1116 max = cp->PipeReadEnds[i];
1121 /* Make sure we have a non-empty set. */
1122 if(max < 0)
1124 /* All pipes have closed. Child has terminated. */
1125 return 1;
1128 /* Run select to block until data are available. Repeat call
1129 until it is not interrupted. */
1130 while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
1131 (errno == EINTR));
1133 /* Check result of select. */
1134 if(numReady == 0)
1136 /* Select's timeout expired. */
1137 wd->Expired = 1;
1138 return 1;
1140 else if(numReady < 0)
1142 /* Select returned an error. Leave the error description in the
1143 pipe buffer. */
1144 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1146 /* Kill the children now. */
1147 kwsysProcess_Kill(cp);
1148 cp->Killed = 0;
1149 cp->SelectError = 1;
1152 return 0;
1153 #else
1154 /* Poll pipes for data since we do not have select. */
1155 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1157 if(cp->PipeReadEnds[i] >= 0)
1159 const int fd = cp->PipeReadEnds[i];
1160 int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
1161 if(n > 0)
1163 /* We have data on this pipe. */
1164 if(i == KWSYSPE_PIPE_SIGNAL)
1166 /* A child process has terminated. */
1167 kwsysProcessDestroy(cp);
1169 else if(data && length)
1171 /* Report this data. */
1172 *data = cp->PipeBuffer;
1173 *length = n;
1174 switch(i)
1176 case KWSYSPE_PIPE_STDOUT:
1177 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1178 case KWSYSPE_PIPE_STDERR:
1179 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1182 return 1;
1184 else if (n == 0) /* EOF */
1186 /* We are done reading from this pipe. */
1187 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1188 --cp->PipesLeft;
1190 else if (n < 0) /* error */
1192 if((errno != EINTR) && (errno != EAGAIN))
1194 strncpy(cp->ErrorMessage,strerror(errno),
1195 KWSYSPE_PIPE_BUFFER_SIZE);
1196 /* Kill the children now. */
1197 kwsysProcess_Kill(cp);
1198 cp->Killed = 0;
1199 cp->SelectError = 1;
1200 return 1;
1206 /* If we have data, break early. */
1207 if(wd->PipeId)
1209 return 1;
1212 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
1213 &timeoutLength))
1215 /* Timeout has already expired. */
1216 wd->Expired = 1;
1217 return 1;
1220 if((timeoutLength.tv_sec == 0) && (timeoutLength.tv_usec == 0))
1222 /* Timeout has already expired. */
1223 wd->Expired = 1;
1224 return 1;
1227 /* Sleep a little, try again. */
1229 unsigned int msec = ((timeoutLength.tv_sec * 1000) +
1230 (timeoutLength.tv_usec / 1000));
1231 if (msec > 100000)
1233 msec = 100000; /* do not sleep more than 100 milliseconds at a time */
1235 kwsysProcess_usleep(msec);
1237 return 0;
1238 #endif
1241 /*--------------------------------------------------------------------------*/
1242 int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
1244 int status = 0;
1245 int prPipe = 0;
1247 /* Make sure we are executing a process. */
1248 if(!cp || cp->State != kwsysProcess_State_Executing)
1250 return 1;
1253 /* Wait for all the pipes to close. Ignore all data. */
1254 while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
1256 if(prPipe == kwsysProcess_Pipe_Timeout)
1258 return 0;
1262 /* Check if there was an error in one of the waitpid calls. */
1263 if(cp->State == kwsysProcess_State_Error)
1265 /* The error message is already in its buffer. Tell
1266 kwsysProcessCleanup to not create it. */
1267 kwsysProcessCleanup(cp, 0);
1268 return 1;
1271 /* Check whether the child reported an error invoking the process. */
1272 if(cp->SelectError)
1274 /* The error message is already in its buffer. Tell
1275 kwsysProcessCleanup to not create it. */
1276 kwsysProcessCleanup(cp, 0);
1277 cp->State = kwsysProcess_State_Error;
1278 return 1;
1281 /* Use the status of the last process in the pipeline. */
1282 status = cp->CommandExitCodes[cp->NumberOfCommands-1];
1284 /* Determine the outcome. */
1285 if(cp->Killed)
1287 /* We killed the child. */
1288 cp->State = kwsysProcess_State_Killed;
1290 else if(cp->TimeoutExpired)
1292 /* The timeout expired. */
1293 cp->State = kwsysProcess_State_Expired;
1295 else if(WIFEXITED(status))
1297 /* The child exited normally. */
1298 cp->State = kwsysProcess_State_Exited;
1299 cp->ExitException = kwsysProcess_Exception_None;
1300 cp->ExitCode = status;
1301 cp->ExitValue = (int)WEXITSTATUS(status);
1303 else if(WIFSIGNALED(status))
1305 /* The child received an unhandled signal. */
1306 cp->State = kwsysProcess_State_Exception;
1307 cp->ExitCode = status;
1308 kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
1310 else
1312 /* Error getting the child return code. */
1313 strcpy(cp->ErrorMessage, "Error getting child return code.");
1314 cp->State = kwsysProcess_State_Error;
1317 /* Normal cleanup. */
1318 kwsysProcessCleanup(cp, 0);
1319 return 1;
1322 /*--------------------------------------------------------------------------*/
1323 void kwsysProcess_Kill(kwsysProcess* cp)
1325 int i;
1327 /* Make sure we are executing a process. */
1328 if(!cp || cp->State != kwsysProcess_State_Executing)
1330 return;
1333 /* First close the child exit report pipe write end to avoid causing a
1334 SIGPIPE when the child terminates and our signal handler tries to
1335 report it after we have already closed the read end. */
1336 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1338 #if !defined(__APPLE__)
1339 /* Close all the pipe read ends. Do this before killing the
1340 children because Cygwin has problems killing processes that are
1341 blocking to wait for writing to their output pipes. */
1342 kwsysProcessClosePipes(cp);
1343 #endif
1345 /* Kill the children. */
1346 cp->Killed = 1;
1347 for(i=0; i < cp->NumberOfCommands; ++i)
1349 int status;
1350 if(cp->ForkPIDs[i])
1352 /* Kill the child. */
1353 kwsysProcessKill(cp->ForkPIDs[i]);
1355 /* Reap the child. Keep trying until the call is not
1356 interrupted. */
1357 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
1361 #if defined(__APPLE__)
1362 /* Close all the pipe read ends. Do this after killing the
1363 children because OS X has problems closing pipe read ends whose
1364 pipes are full and still have an open write end. */
1365 kwsysProcessClosePipes(cp);
1366 #endif
1368 cp->CommandsLeft = 0;
1371 /*--------------------------------------------------------------------------*/
1372 /* Initialize a process control structure for kwsysProcess_Execute. */
1373 static int kwsysProcessInitialize(kwsysProcess* cp)
1375 int i;
1376 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1378 cp->PipeReadEnds[i] = -1;
1380 cp->SignalPipe = -1;
1381 cp->SelectError = 0;
1382 cp->StartTime.tv_sec = -1;
1383 cp->StartTime.tv_usec = -1;
1384 cp->TimeoutTime.tv_sec = -1;
1385 cp->TimeoutTime.tv_usec = -1;
1386 cp->TimeoutExpired = 0;
1387 cp->PipesLeft = 0;
1388 cp->CommandsLeft = 0;
1389 #if KWSYSPE_USE_SELECT
1390 FD_ZERO(&cp->PipeSet);
1391 #endif
1392 cp->State = kwsysProcess_State_Starting;
1393 cp->Killed = 0;
1394 cp->ExitException = kwsysProcess_Exception_None;
1395 cp->ExitCode = 1;
1396 cp->ExitValue = 1;
1397 cp->ErrorMessage[0] = 0;
1398 strcpy(cp->ExitExceptionString, "No exception");
1400 if(cp->ForkPIDs)
1402 free(cp->ForkPIDs);
1404 cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
1405 if(!cp->ForkPIDs)
1407 return 0;
1409 memset(cp->ForkPIDs, 0, sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
1411 if(cp->CommandExitCodes)
1413 free(cp->CommandExitCodes);
1415 cp->CommandExitCodes = (int*)malloc(sizeof(int)*
1416 (size_t)(cp->NumberOfCommands));
1417 if(!cp->CommandExitCodes)
1419 return 0;
1421 memset(cp->CommandExitCodes, 0, sizeof(int)*(size_t)(cp->NumberOfCommands));
1423 /* Allocate memory to save the real working directory. */
1424 if ( cp->WorkingDirectory )
1426 #if defined(MAXPATHLEN)
1427 cp->RealWorkingDirectoryLength = MAXPATHLEN;
1428 #elif defined(PATH_MAX)
1429 cp->RealWorkingDirectoryLength = PATH_MAX;
1430 #else
1431 cp->RealWorkingDirectoryLength = 4096;
1432 #endif
1433 cp->RealWorkingDirectory =
1434 malloc((size_t)(cp->RealWorkingDirectoryLength));
1435 if(!cp->RealWorkingDirectory)
1437 return 0;
1441 return 1;
1444 /*--------------------------------------------------------------------------*/
1445 /* Free all resources used by the given kwsysProcess instance that were
1446 allocated by kwsysProcess_Execute. */
1447 static void kwsysProcessCleanup(kwsysProcess* cp, int error)
1449 int i;
1451 if(error)
1453 /* We are cleaning up due to an error. Report the error message
1454 if one has not been provided already. */
1455 if(cp->ErrorMessage[0] == 0)
1457 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1460 /* Set the error state. */
1461 cp->State = kwsysProcess_State_Error;
1463 /* Kill any children already started. */
1464 if(cp->ForkPIDs)
1466 int status;
1467 for(i=0; i < cp->NumberOfCommands; ++i)
1469 if(cp->ForkPIDs[i])
1471 /* Kill the child. */
1472 kwsysProcessKill(cp->ForkPIDs[i]);
1474 /* Reap the child. Keep trying until the call is not
1475 interrupted. */
1476 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
1477 (errno == EINTR));
1482 /* Restore the working directory. */
1483 if(cp->RealWorkingDirectory)
1485 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
1489 /* If not creating a detached child, remove this object from the
1490 global set of process objects that wish to be notified when a
1491 child exits. */
1492 if(!cp->OptionDetach)
1494 kwsysProcessesRemove(cp);
1497 /* Free memory. */
1498 if(cp->ForkPIDs)
1500 free(cp->ForkPIDs);
1501 cp->ForkPIDs = 0;
1503 if(cp->RealWorkingDirectory)
1505 free(cp->RealWorkingDirectory);
1506 cp->RealWorkingDirectory = 0;
1509 /* Close pipe handles. */
1510 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1512 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1516 /*--------------------------------------------------------------------------*/
1517 /* Close the given file descriptor if it is open. Reset its value to -1. */
1518 static void kwsysProcessCleanupDescriptor(int* pfd)
1520 if(pfd && *pfd >= 0)
1522 /* Keep trying to close until it is not interrupted by a
1523 * signal. */
1524 while((close(*pfd) < 0) && (errno == EINTR));
1525 *pfd = -1;
1529 /*--------------------------------------------------------------------------*/
1530 static void kwsysProcessClosePipes(kwsysProcess* cp)
1532 int i;
1534 /* Close any pipes that are still open. */
1535 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1537 if(cp->PipeReadEnds[i] >= 0)
1539 #if KWSYSPE_USE_SELECT
1540 /* If the pipe was reported by the last call to select, we must
1541 read from it. This is needed to satisfy the suggestions from
1542 "man select_tut" and is not needed for the polling
1543 implementation. Ignore the data. */
1544 if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1546 /* We are handling this pipe now. Remove it from the set. */
1547 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1549 /* The pipe is ready to read without blocking. Keep trying to
1550 read until the operation is not interrupted. */
1551 while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
1552 KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
1554 #endif
1556 /* We are done reading from this pipe. */
1557 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1558 --cp->PipesLeft;
1563 /*--------------------------------------------------------------------------*/
1564 static int kwsysProcessSetNonBlocking(int fd)
1566 int flags = fcntl(fd, F_GETFL);
1567 if(flags >= 0)
1569 flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
1571 return flags >= 0;
1574 /*--------------------------------------------------------------------------*/
1575 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
1576 kwsysProcessCreateInformation* si, int* readEnd)
1578 /* Setup the process's stdin. */
1579 if(prIndex > 0)
1581 si->StdIn = *readEnd;
1582 *readEnd = 0;
1584 else if(cp->PipeFileSTDIN)
1586 /* Open a file for the child's stdin to read. */
1587 si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
1588 if(si->StdIn < 0)
1590 return 0;
1593 /* Set close-on-exec flag on the pipe's end. */
1594 if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
1596 return 0;
1599 else if(cp->PipeSharedSTDIN)
1601 si->StdIn = 0;
1603 else if(cp->PipeNativeSTDIN[0] >= 0)
1605 si->StdIn = cp->PipeNativeSTDIN[0];
1607 /* Set close-on-exec flag on the pipe's ends. The read end will
1608 be dup2-ed into the stdin descriptor after the fork but before
1609 the exec. */
1610 if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
1611 (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
1613 return 0;
1616 else
1618 si->StdIn = -1;
1621 /* Setup the process's stdout. */
1623 /* Create the pipe. */
1624 int p[2];
1625 if(pipe(p) < 0)
1627 return 0;
1629 *readEnd = p[0];
1630 si->StdOut = p[1];
1632 /* Set close-on-exec flag on the pipe's ends. */
1633 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
1634 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
1636 return 0;
1640 /* Replace the stdout pipe with a file if requested. In this case
1641 the select call will report that stdout is closed immediately. */
1642 if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
1644 if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
1646 return 0;
1650 /* Replace the stdout pipe with the parent's if requested. In this
1651 case the select call will report that stderr is closed
1652 immediately. */
1653 if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
1655 kwsysProcessCleanupDescriptor(&si->StdOut);
1656 si->StdOut = 1;
1659 /* Replace the stdout pipe with the native pipe provided if any. In
1660 this case the select call will report that stdout is closed
1661 immediately. */
1662 if(prIndex == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1] >= 0)
1664 if(!kwsysProcessSetupOutputPipeNative(&si->StdOut, cp->PipeNativeSTDOUT))
1666 return 0;
1670 /* Create the error reporting pipe. */
1671 if(pipe(si->ErrorPipe) < 0)
1673 return 0;
1676 /* Set close-on-exec flag on the error pipe's write end. */
1677 if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
1679 return 0;
1682 /* Fork off a child process. */
1683 cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
1684 if(cp->ForkPIDs[prIndex] < 0)
1686 return 0;
1689 if(cp->ForkPIDs[prIndex] == 0)
1691 /* Close the read end of the error reporting pipe. */
1692 close(si->ErrorPipe[0]);
1694 /* Setup the stdin, stdout, and stderr pipes. */
1695 if(si->StdIn > 0)
1697 dup2(si->StdIn, 0);
1699 else if(si->StdIn < 0)
1701 close(0);
1703 if(si->StdOut != 1)
1705 dup2(si->StdOut, 1);
1707 if(si->StdErr != 2)
1709 dup2(si->StdErr, 2);
1712 /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1713 All other pipe handles will be closed when exec succeeds. */
1714 fcntl(0, F_SETFD, 0);
1715 fcntl(1, F_SETFD, 0);
1716 fcntl(2, F_SETFD, 0);
1718 /* Restore all default signal handlers. */
1719 kwsysProcessRestoreDefaultSignalHandlers();
1721 /* Execute the real process. If successful, this does not return. */
1722 execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
1724 /* Failure. Report error to parent and terminate. */
1725 kwsysProcessChildErrorExit(si->ErrorPipe[1]);
1728 /* A child has been created. */
1729 ++cp->CommandsLeft;
1731 /* We are done with the error reporting pipe write end. */
1732 kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1734 /* Block until the child's exec call succeeds and closes the error
1735 pipe or writes data to the pipe to report an error. */
1737 kwsysProcess_ssize_t total = 0;
1738 kwsysProcess_ssize_t n = 1;
1739 /* Read the entire error message up to the length of our buffer. */
1740 while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
1742 /* Keep trying to read until the operation is not interrupted. */
1743 while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
1744 (size_t)(KWSYSPE_PIPE_BUFFER_SIZE-total))) < 0) &&
1745 (errno == EINTR));
1746 if(n > 0)
1748 total += n;
1752 /* We are done with the error reporting pipe read end. */
1753 kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1755 if(total > 0)
1757 /* The child failed to execute the process. */
1758 return 0;
1762 /* Successfully created this child process. */
1763 if(prIndex > 0 || si->StdIn > 0)
1765 /* The parent process does not need the input pipe read end. */
1766 kwsysProcessCleanupDescriptor(&si->StdIn);
1769 /* The parent process does not need the output pipe write ends. */
1770 if(si->StdOut != 1)
1772 kwsysProcessCleanupDescriptor(&si->StdOut);
1775 return 1;
1778 /*--------------------------------------------------------------------------*/
1779 static void kwsysProcessDestroy(kwsysProcess* cp)
1781 /* A child process has terminated. Reap it if it is one handled by
1782 this object. */
1783 int i;
1784 for(i=0; i < cp->NumberOfCommands; ++i)
1786 if(cp->ForkPIDs[i])
1788 int result;
1789 while(((result = waitpid(cp->ForkPIDs[i],
1790 &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
1791 (errno == EINTR));
1792 if(result > 0)
1794 /* This child has termianted. */
1795 cp->ForkPIDs[i] = 0;
1796 if(--cp->CommandsLeft == 0)
1798 /* All children have terminated. Close the signal pipe
1799 write end so that no more notifications are sent to this
1800 object. */
1801 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1803 /* TODO: Once the children have terminated, switch
1804 WaitForData to use a non-blocking read to get the
1805 rest of the data from the pipe. This is needed when
1806 grandchildren keep the output pipes open. */
1809 else if(result < 0 && cp->State != kwsysProcess_State_Error)
1811 /* Unexpected error. Report the first time this happens. */
1812 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1813 cp->State = kwsysProcess_State_Error;
1819 /*--------------------------------------------------------------------------*/
1820 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
1822 int fout;
1823 if(!name)
1825 return 1;
1828 /* Close the existing descriptor. */
1829 kwsysProcessCleanupDescriptor(p);
1831 /* Open a file for the pipe to write (permissions 644). */
1832 if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC,
1833 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
1835 return 0;
1838 /* Set close-on-exec flag on the pipe's end. */
1839 if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
1841 return 0;
1844 /* Assign the replacement descriptor. */
1845 *p = fout;
1846 return 1;
1849 /*--------------------------------------------------------------------------*/
1850 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
1852 /* Close the existing descriptor. */
1853 kwsysProcessCleanupDescriptor(p);
1855 /* Set close-on-exec flag on the pipe's ends. The proper end will
1856 be dup2-ed into the standard descriptor number after fork but
1857 before exec. */
1858 if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
1859 (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
1861 return 0;
1864 /* Assign the replacement descriptor. */
1865 *p = des[1];
1866 return 1;
1869 /*--------------------------------------------------------------------------*/
1870 /* Get the time at which either the process or user timeout will
1871 expire. Returns 1 if the user timeout is first, and 0 otherwise. */
1872 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
1873 kwsysProcessTime* timeoutTime)
1875 /* The first time this is called, we need to calculate the time at
1876 which the child will timeout. */
1877 if(cp->Timeout && cp->TimeoutTime.tv_sec < 0)
1879 kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
1880 cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
1883 /* Start with process timeout. */
1884 *timeoutTime = cp->TimeoutTime;
1886 /* Check if the user timeout is earlier. */
1887 if(userTimeout)
1889 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1890 kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
1891 kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
1892 userTimeoutLength);
1893 if(timeoutTime->tv_sec < 0 ||
1894 kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
1896 *timeoutTime = userTimeoutTime;
1897 return 1;
1900 return 0;
1903 /*--------------------------------------------------------------------------*/
1904 /* Get the length of time before the given timeout time arrives.
1905 Returns 1 if the time has already arrived, and 0 otherwise. */
1906 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
1907 double* userTimeout,
1908 kwsysProcessTimeNative* timeoutLength)
1910 if(timeoutTime->tv_sec < 0)
1912 /* No timeout time has been requested. */
1913 return 0;
1915 else
1917 /* Calculate the remaining time. */
1918 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1919 kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
1920 currentTime);
1921 if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
1923 /* Caller has explicitly requested a zero timeout. */
1924 timeLeft.tv_sec = 0;
1925 timeLeft.tv_usec = 0;
1928 if(timeLeft.tv_sec < 0)
1930 /* Timeout has already expired. */
1931 return 1;
1933 else
1935 /* There is some time left. */
1936 timeoutLength->tv_sec = timeLeft.tv_sec;
1937 timeoutLength->tv_usec = timeLeft.tv_usec;
1938 return 0;
1943 /*--------------------------------------------------------------------------*/
1944 static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
1946 kwsysProcessTime current;
1947 kwsysProcessTimeNative current_native;
1948 gettimeofday(&current_native, 0);
1949 current.tv_sec = (long)current_native.tv_sec;
1950 current.tv_usec = (long)current_native.tv_usec;
1951 return current;
1954 /*--------------------------------------------------------------------------*/
1955 static double kwsysProcessTimeToDouble(kwsysProcessTime t)
1957 return (double)t.tv_sec + (double)(t.tv_usec)*0.000001;
1960 /*--------------------------------------------------------------------------*/
1961 static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
1963 kwsysProcessTime t;
1964 t.tv_sec = (long)d;
1965 t.tv_usec = (long)((d-(double)(t.tv_sec))*1000000);
1966 return t;
1969 /*--------------------------------------------------------------------------*/
1970 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
1972 return ((in1.tv_sec < in2.tv_sec) ||
1973 ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
1976 /*--------------------------------------------------------------------------*/
1977 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
1979 kwsysProcessTime out;
1980 out.tv_sec = in1.tv_sec + in2.tv_sec;
1981 out.tv_usec = in1.tv_usec + in2.tv_usec;
1982 if(out.tv_usec > 1000000)
1984 out.tv_usec -= 1000000;
1985 out.tv_sec += 1;
1987 return out;
1990 /*--------------------------------------------------------------------------*/
1991 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
1993 kwsysProcessTime out;
1994 out.tv_sec = in1.tv_sec - in2.tv_sec;
1995 out.tv_usec = in1.tv_usec - in2.tv_usec;
1996 if(out.tv_usec < 0)
1998 out.tv_usec += 1000000;
1999 out.tv_sec -= 1;
2001 return out;
2004 /*--------------------------------------------------------------------------*/
2005 #define KWSYSPE_CASE(type, str) \
2006 cp->ExitException = kwsysProcess_Exception_##type; \
2007 strcpy(cp->ExitExceptionString, str)
2008 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
2010 switch (sig)
2012 #ifdef SIGSEGV
2013 case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
2014 #endif
2015 #ifdef SIGBUS
2016 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2017 case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
2018 # endif
2019 #endif
2020 #ifdef SIGFPE
2021 case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
2022 #endif
2023 #ifdef SIGILL
2024 case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
2025 #endif
2026 #ifdef SIGINT
2027 case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
2028 #endif
2029 #ifdef SIGABRT
2030 case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
2031 #endif
2032 #ifdef SIGKILL
2033 case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
2034 #endif
2035 #ifdef SIGTERM
2036 case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
2037 #endif
2038 #ifdef SIGHUP
2039 case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
2040 #endif
2041 #ifdef SIGQUIT
2042 case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
2043 #endif
2044 #ifdef SIGTRAP
2045 case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
2046 #endif
2047 #ifdef SIGIOT
2048 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2049 case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
2050 # endif
2051 #endif
2052 #ifdef SIGUSR1
2053 case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
2054 #endif
2055 #ifdef SIGUSR2
2056 case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
2057 #endif
2058 #ifdef SIGPIPE
2059 case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
2060 #endif
2061 #ifdef SIGALRM
2062 case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
2063 #endif
2064 #ifdef SIGSTKFLT
2065 case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
2066 #endif
2067 #ifdef SIGCHLD
2068 case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
2069 #elif defined(SIGCLD)
2070 case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
2071 #endif
2072 #ifdef SIGCONT
2073 case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
2074 #endif
2075 #ifdef SIGSTOP
2076 case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
2077 #endif
2078 #ifdef SIGTSTP
2079 case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
2080 #endif
2081 #ifdef SIGTTIN
2082 case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
2083 #endif
2084 #ifdef SIGTTOU
2085 case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
2086 #endif
2087 #ifdef SIGURG
2088 case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
2089 #endif
2090 #ifdef SIGXCPU
2091 case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
2092 #endif
2093 #ifdef SIGXFSZ
2094 case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
2095 #endif
2096 #ifdef SIGVTALRM
2097 case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
2098 #endif
2099 #ifdef SIGPROF
2100 case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
2101 #endif
2102 #ifdef SIGWINCH
2103 case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
2104 #endif
2105 #ifdef SIGPOLL
2106 case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
2107 #endif
2108 #ifdef SIGIO
2109 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2110 case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
2111 # endif
2112 #endif
2113 #ifdef SIGPWR
2114 case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
2115 #endif
2116 #ifdef SIGSYS
2117 case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
2118 #endif
2119 #ifdef SIGUNUSED
2120 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2121 case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
2122 # endif
2123 #endif
2124 default:
2125 cp->ExitException = kwsysProcess_Exception_Other;
2126 sprintf(cp->ExitExceptionString, "Signal %d", sig);
2127 break;
2130 #undef KWSYSPE_CASE
2132 /*--------------------------------------------------------------------------*/
2133 /* When the child process encounters an error before its program is
2134 invoked, this is called to report the error to the parent and
2135 exit. */
2136 static void kwsysProcessChildErrorExit(int errorPipe)
2138 /* Construct the error message. */
2139 char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
2140 kwsysProcess_ssize_t result;
2141 strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
2143 /* Report the error to the parent through the special pipe. */
2144 result=write(errorPipe, buffer, strlen(buffer));
2145 (void)result;
2147 /* Terminate without cleanup. */
2148 _exit(1);
2151 /*--------------------------------------------------------------------------*/
2152 /* Restores all signal handlers to their default values. */
2153 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2155 struct sigaction act;
2156 memset(&act, 0, sizeof(struct sigaction));
2157 act.sa_handler = SIG_DFL;
2158 #ifdef SIGHUP
2159 sigaction(SIGHUP, &act, 0);
2160 #endif
2161 #ifdef SIGINT
2162 sigaction(SIGINT, &act, 0);
2163 #endif
2164 #ifdef SIGQUIT
2165 sigaction(SIGQUIT, &act, 0);
2166 #endif
2167 #ifdef SIGILL
2168 sigaction(SIGILL, &act, 0);
2169 #endif
2170 #ifdef SIGTRAP
2171 sigaction(SIGTRAP, &act, 0);
2172 #endif
2173 #ifdef SIGABRT
2174 sigaction(SIGABRT, &act, 0);
2175 #endif
2176 #ifdef SIGIOT
2177 sigaction(SIGIOT, &act, 0);
2178 #endif
2179 #ifdef SIGBUS
2180 sigaction(SIGBUS, &act, 0);
2181 #endif
2182 #ifdef SIGFPE
2183 sigaction(SIGFPE, &act, 0);
2184 #endif
2185 #ifdef SIGUSR1
2186 sigaction(SIGUSR1, &act, 0);
2187 #endif
2188 #ifdef SIGSEGV
2189 sigaction(SIGSEGV, &act, 0);
2190 #endif
2191 #ifdef SIGUSR2
2192 sigaction(SIGUSR2, &act, 0);
2193 #endif
2194 #ifdef SIGPIPE
2195 sigaction(SIGPIPE, &act, 0);
2196 #endif
2197 #ifdef SIGALRM
2198 sigaction(SIGALRM, &act, 0);
2199 #endif
2200 #ifdef SIGTERM
2201 sigaction(SIGTERM, &act, 0);
2202 #endif
2203 #ifdef SIGSTKFLT
2204 sigaction(SIGSTKFLT, &act, 0);
2205 #endif
2206 #ifdef SIGCLD
2207 sigaction(SIGCLD, &act, 0);
2208 #endif
2209 #ifdef SIGCHLD
2210 sigaction(SIGCHLD, &act, 0);
2211 #endif
2212 #ifdef SIGCONT
2213 sigaction(SIGCONT, &act, 0);
2214 #endif
2215 #ifdef SIGTSTP
2216 sigaction(SIGTSTP, &act, 0);
2217 #endif
2218 #ifdef SIGTTIN
2219 sigaction(SIGTTIN, &act, 0);
2220 #endif
2221 #ifdef SIGTTOU
2222 sigaction(SIGTTOU, &act, 0);
2223 #endif
2224 #ifdef SIGURG
2225 sigaction(SIGURG, &act, 0);
2226 #endif
2227 #ifdef SIGXCPU
2228 sigaction(SIGXCPU, &act, 0);
2229 #endif
2230 #ifdef SIGXFSZ
2231 sigaction(SIGXFSZ, &act, 0);
2232 #endif
2233 #ifdef SIGVTALRM
2234 sigaction(SIGVTALRM, &act, 0);
2235 #endif
2236 #ifdef SIGPROF
2237 sigaction(SIGPROF, &act, 0);
2238 #endif
2239 #ifdef SIGWINCH
2240 sigaction(SIGWINCH, &act, 0);
2241 #endif
2242 #ifdef SIGPOLL
2243 sigaction(SIGPOLL, &act, 0);
2244 #endif
2245 #ifdef SIGIO
2246 sigaction(SIGIO, &act, 0);
2247 #endif
2248 #ifdef SIGPWR
2249 sigaction(SIGPWR, &act, 0);
2250 #endif
2251 #ifdef SIGSYS
2252 sigaction(SIGSYS, &act, 0);
2253 #endif
2254 #ifdef SIGUNUSED
2255 sigaction(SIGUNUSED, &act, 0);
2256 #endif
2259 /*--------------------------------------------------------------------------*/
2260 static void kwsysProcessExit(void)
2262 _exit(0);
2265 /*--------------------------------------------------------------------------*/
2266 static pid_t kwsysProcessFork(kwsysProcess* cp,
2267 kwsysProcessCreateInformation* si)
2269 /* Create a detached process if requested. */
2270 if(cp->OptionDetach)
2272 /* Create an intermediate process. */
2273 pid_t middle_pid = fork();
2274 if(middle_pid < 0)
2276 /* Fork failed. Return as if we were not detaching. */
2277 return middle_pid;
2279 else if(middle_pid == 0)
2281 /* This is the intermediate process. Create the real child. */
2282 pid_t child_pid = fork();
2283 if(child_pid == 0)
2285 /* This is the real child process. There is nothing to do here. */
2286 return 0;
2288 else
2290 /* Use the error pipe to report the pid to the real parent. */
2291 while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
2292 (errno == EINTR));
2294 /* Exit without cleanup. The parent holds all resources. */
2295 kwsysProcessExit();
2296 return 0; /* Never reached, but avoids SunCC warning. */
2299 else
2301 /* This is the original parent process. The intermediate
2302 process will use the error pipe to report the pid of the
2303 detached child. */
2304 pid_t child_pid;
2305 int status;
2306 while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
2307 (errno == EINTR));
2309 /* Wait for the intermediate process to exit and clean it up. */
2310 while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
2311 return child_pid;
2314 else
2316 /* Not creating a detached process. Use normal fork. */
2317 return fork();
2321 /*--------------------------------------------------------------------------*/
2322 /* We try to obtain process information by invoking the ps command.
2323 Here we define the command to call on each platform and the
2324 corresponding parsing format string. The parsing format should
2325 have two integers to store: the pid and then the ppid. */
2326 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
2327 # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2328 # define KWSYSPE_PS_FORMAT "%d %d\n"
2329 #elif defined(__hpux) || defined(__sparc) || defined(__sgi) || defined(_AIX)
2330 # define KWSYSPE_PS_COMMAND "ps -ef"
2331 # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
2332 #elif defined(__CYGWIN__)
2333 # define KWSYSPE_PS_COMMAND "ps aux"
2334 # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
2335 #endif
2337 /*--------------------------------------------------------------------------*/
2338 static void kwsysProcessKill(pid_t process_id)
2340 #if defined(__linux__) || defined(__CYGWIN__)
2341 DIR* procdir;
2342 #endif
2344 /* Kill the process now to make sure it does not create more
2345 children. Do not reap it yet so we can identify its existing
2346 children. There is a small race condition here. If the child
2347 forks after we begin looking for children below but before it
2348 receives this kill signal we might miss a child. Also we might
2349 not be able to catch up to a fork bomb. */
2350 kill(process_id, SIGKILL);
2352 /* Kill all children if we can find them. */
2353 #if defined(__linux__) || defined(__CYGWIN__)
2354 /* First try using the /proc filesystem. */
2355 if((procdir = opendir("/proc")) != NULL)
2357 #if defined(MAXPATHLEN)
2358 char fname[MAXPATHLEN];
2359 #elif defined(PATH_MAX)
2360 char fname[PATH_MAX];
2361 #else
2362 char fname[4096];
2363 #endif
2364 char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
2365 struct dirent* d;
2367 /* Each process has a directory in /proc whose name is the pid.
2368 Within this directory is a file called stat that has the
2369 following format:
2371 pid (command line) status ppid ...
2373 We want to get the ppid for all processes. Those that have
2374 process_id as their parent should be recursively killed. */
2375 for(d = readdir(procdir); d; d = readdir(procdir))
2377 int pid;
2378 if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
2380 struct stat finfo;
2381 sprintf(fname, "/proc/%d/stat", pid);
2382 if(stat(fname, &finfo) == 0)
2384 FILE* f = fopen(fname, "r");
2385 if(f)
2387 size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
2388 buffer[nread] = '\0';
2389 if(nread > 0)
2391 const char* rparen = strrchr(buffer, ')');
2392 int ppid;
2393 if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
2395 if(ppid == process_id)
2397 /* Recursively kill this child and its children. */
2398 kwsysProcessKill(pid);
2402 fclose(f);
2407 closedir(procdir);
2409 else
2410 #endif
2412 #if defined(KWSYSPE_PS_COMMAND)
2413 /* Try running "ps" to get the process information. */
2414 FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
2416 /* Make sure the process started and provided a valid header. */
2417 if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
2419 /* Look for processes whose parent is the process being killed. */
2420 int pid, ppid;
2421 while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
2423 if(ppid == process_id)
2425 /* Recursively kill this child and its children. */
2426 kwsysProcessKill(pid);
2431 /* We are done with the ps process. */
2432 if(ps)
2434 pclose(ps);
2436 #endif
2440 /*--------------------------------------------------------------------------*/
2441 /* Global set of executing processes for use by the signal handler.
2442 This global instance will be zero-initialized by the compiler. */
2443 typedef struct kwsysProcessInstances_s
2445 int Count;
2446 int Size;
2447 kwsysProcess** Processes;
2448 } kwsysProcessInstances;
2449 static kwsysProcessInstances kwsysProcesses;
2451 /* The old SIGCHLD handler. */
2452 static struct sigaction kwsysProcessesOldSigChldAction;
2454 /*--------------------------------------------------------------------------*/
2455 static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
2457 /* Block SIGCHLD while we update the set of pipes to check.
2458 TODO: sigprocmask is undefined for threaded apps. See
2459 pthread_sigmask. */
2460 sigset_t newset;
2461 sigset_t oldset;
2462 sigemptyset(&newset);
2463 sigaddset(&newset, SIGCHLD);
2464 sigprocmask(SIG_BLOCK, &newset, &oldset);
2466 /* Store the new set in that seen by the signal handler. */
2467 kwsysProcesses = *newProcesses;
2469 /* Restore the signal mask to the previous setting. */
2470 sigprocmask(SIG_SETMASK, &oldset, 0);
2473 /*--------------------------------------------------------------------------*/
2474 static int kwsysProcessesAdd(kwsysProcess* cp)
2476 /* Create a pipe through which the signal handler can notify the
2477 given process object that a child has exited. */
2479 /* Create the pipe. */
2480 int p[2];
2481 if(pipe(p) < 0)
2483 return 0;
2486 /* Store the pipes now to be sure they are cleaned up later. */
2487 cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
2488 cp->SignalPipe = p[1];
2490 /* Switch the pipe to non-blocking mode so that reading a byte can
2491 be an atomic test-and-set. */
2492 if(!kwsysProcessSetNonBlocking(p[0]) ||
2493 !kwsysProcessSetNonBlocking(p[1]))
2495 return 0;
2498 /* The children do not need this pipe. Set close-on-exec flag on
2499 the pipe's ends. */
2500 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
2501 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
2503 return 0;
2507 /* Attempt to add the given signal pipe to the signal handler set. */
2510 /* Make sure there is enough space for the new signal pipe. */
2511 kwsysProcessInstances oldProcesses = kwsysProcesses;
2512 kwsysProcessInstances newProcesses = oldProcesses;
2513 if(oldProcesses.Count == oldProcesses.Size)
2515 /* Start with enough space for a small number of process instances
2516 and double the size each time more is needed. */
2517 newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
2519 /* Try allocating the new block of memory. */
2520 if((newProcesses.Processes = ((kwsysProcess**)
2521 malloc((size_t)(newProcesses.Size)*
2522 sizeof(kwsysProcess*)))))
2524 /* Copy the old pipe set to the new memory. */
2525 if(oldProcesses.Count > 0)
2527 memcpy(newProcesses.Processes, oldProcesses.Processes,
2528 ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
2531 else
2533 /* Failed to allocate memory for the new signal pipe set. */
2534 return 0;
2538 /* Append the new signal pipe to the set. */
2539 newProcesses.Processes[newProcesses.Count++] = cp;
2541 /* Store the new set in that seen by the signal handler. */
2542 kwsysProcessesUpdate(&newProcesses);
2544 /* Free the original pipes if new ones were allocated. */
2545 if(newProcesses.Processes != oldProcesses.Processes)
2547 free(oldProcesses.Processes);
2550 /* If this is the first process, enable the signal handler. */
2551 if(newProcesses.Count == 1)
2553 /* Install our handler for SIGCHLD. Repeat call until it is not
2554 interrupted. */
2555 struct sigaction newSigChldAction;
2556 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2557 #if KWSYSPE_USE_SIGINFO
2558 newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
2559 newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2560 # ifdef SA_RESTART
2561 newSigChldAction.sa_flags |= SA_RESTART;
2562 # endif
2563 #else
2564 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2565 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2566 #endif
2567 while((sigaction(SIGCHLD, &newSigChldAction,
2568 &kwsysProcessesOldSigChldAction) < 0) &&
2569 (errno == EINTR));
2573 return 1;
2576 /*--------------------------------------------------------------------------*/
2577 static void kwsysProcessesRemove(kwsysProcess* cp)
2579 /* Attempt to remove the given signal pipe from the signal handler set. */
2581 /* Find the given process in the set. */
2582 kwsysProcessInstances newProcesses = kwsysProcesses;
2583 int i;
2584 for(i=0; i < newProcesses.Count; ++i)
2586 if(newProcesses.Processes[i] == cp)
2588 break;
2591 if(i < newProcesses.Count)
2593 /* Remove the process from the set. */
2594 --newProcesses.Count;
2595 for(; i < newProcesses.Count; ++i)
2597 newProcesses.Processes[i] = newProcesses.Processes[i+1];
2600 /* If this was the last process, disable the signal handler. */
2601 if(newProcesses.Count == 0)
2603 /* Restore the SIGCHLD handler. Repeat call until it is not
2604 interrupted. */
2605 while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
2606 (errno == EINTR));
2608 /* Free the table of process pointers since it is now empty.
2609 This is safe because the signal handler has been removed. */
2610 newProcesses.Size = 0;
2611 free(newProcesses.Processes);
2612 newProcesses.Processes = 0;
2615 /* Store the new set in that seen by the signal handler. */
2616 kwsysProcessesUpdate(&newProcesses);
2620 /* Close the pipe through which the signal handler may have notified
2621 the given process object that a child has exited. */
2622 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
2625 /*--------------------------------------------------------------------------*/
2626 static void kwsysProcessesSignalHandler(int signum
2627 #if KWSYSPE_USE_SIGINFO
2628 , siginfo_t* info, void* ucontext
2629 #endif
2632 (void)signum;
2633 #if KWSYSPE_USE_SIGINFO
2634 (void)info;
2635 (void)ucontext;
2636 #endif
2638 /* Signal all process objects that a child has terminated. */
2640 int i;
2641 for(i=0; i < kwsysProcesses.Count; ++i)
2643 /* Set the pipe in a signalled state. */
2644 char buf = 1;
2645 kwsysProcess* cp = kwsysProcesses.Processes[i];
2646 kwsysProcess_ssize_t status=
2647 read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
2648 status=write(cp->SignalPipe, &buf, 1);
2653 #if !KWSYSPE_USE_SIGINFO
2654 /* Re-Install our handler for SIGCHLD. Repeat call until it is not
2655 interrupted. */
2657 struct sigaction newSigChldAction;
2658 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2659 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2660 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2661 while((sigaction(SIGCHLD, &newSigChldAction,
2662 &kwsysProcessesOldSigChldAction) < 0) &&
2663 (errno == EINTR));
2665 #endif
2668 /*--------------------------------------------------------------------------*/
2669 static int kwsysProcessAppendByte(char* local,
2670 char** begin, char** end,
2671 int* size, char c)
2673 /* Allocate space for the character. */
2674 if((*end - *begin) >= *size)
2676 kwsysProcess_ptrdiff_t length = *end - *begin;
2677 char* newBuffer = (char*)malloc((size_t)(*size*2));
2678 if(!newBuffer)
2680 return 0;
2682 memcpy(newBuffer, *begin, (size_t)(length)*sizeof(char));
2683 if(*begin != local)
2685 free(*begin);
2687 *begin = newBuffer;
2688 *end = *begin + length;
2689 *size *= 2;
2692 /* Store the character. */
2693 *(*end)++ = c;
2694 return 1;
2697 /*--------------------------------------------------------------------------*/
2698 static int kwsysProcessAppendArgument(char** local,
2699 char*** begin, char*** end,
2700 int* size,
2701 char* arg_local,
2702 char** arg_begin, char** arg_end,
2703 int* arg_size)
2705 /* Append a null-terminator to the argument string. */
2706 if(!kwsysProcessAppendByte(arg_local, arg_begin, arg_end, arg_size, '\0'))
2708 return 0;
2711 /* Allocate space for the argument pointer. */
2712 if((*end - *begin) >= *size)
2714 kwsysProcess_ptrdiff_t length = *end - *begin;
2715 char** newPointers = (char**)malloc((size_t)(*size)*2*sizeof(char*));
2716 if(!newPointers)
2718 return 0;
2720 memcpy(newPointers, *begin, (size_t)(length)*sizeof(char*));
2721 if(*begin != local)
2723 free(*begin);
2725 *begin = newPointers;
2726 *end = *begin + length;
2727 *size *= 2;
2730 /* Allocate space for the argument string. */
2731 **end = (char*)malloc((size_t)(*arg_end - *arg_begin));
2732 if(!**end)
2734 return 0;
2737 /* Store the argument in the command array. */
2738 memcpy(**end, *arg_begin,(size_t)(*arg_end - *arg_begin));
2739 ++(*end);
2741 /* Reset the argument to be empty. */
2742 *arg_end = *arg_begin;
2744 return 1;
2747 /*--------------------------------------------------------------------------*/
2748 #define KWSYSPE_LOCAL_BYTE_COUNT 1024
2749 #define KWSYSPE_LOCAL_ARGS_COUNT 32
2750 static char** kwsysProcessParseVerbatimCommand(const char* command)
2752 /* Create a buffer for argument pointers during parsing. */
2753 char* local_pointers[KWSYSPE_LOCAL_ARGS_COUNT];
2754 int pointers_size = KWSYSPE_LOCAL_ARGS_COUNT;
2755 char** pointer_begin = local_pointers;
2756 char** pointer_end = pointer_begin;
2758 /* Create a buffer for argument strings during parsing. */
2759 char local_buffer[KWSYSPE_LOCAL_BYTE_COUNT];
2760 int buffer_size = KWSYSPE_LOCAL_BYTE_COUNT;
2761 char* buffer_begin = local_buffer;
2762 char* buffer_end = buffer_begin;
2764 /* Parse the command string. Try to behave like a UNIX shell. */
2765 char** newCommand = 0;
2766 const char* c = command;
2767 int in_argument = 0;
2768 int in_escape = 0;
2769 int in_single = 0;
2770 int in_double = 0;
2771 int failed = 0;
2772 for(;*c; ++c)
2774 if(in_escape)
2776 /* This character is escaped so do no special handling. */
2777 if(!in_argument)
2779 in_argument = 1;
2781 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2782 &buffer_end, &buffer_size, *c))
2784 failed = 1;
2785 break;
2787 in_escape = 0;
2789 else if(*c == '\\' && !in_single)
2791 /* The next character should be escaped. */
2792 in_escape = 1;
2794 else if(*c == '\'' && !in_double)
2796 /* Enter or exit single-quote state. */
2797 if(in_single)
2799 in_single = 0;
2801 else
2803 in_single = 1;
2804 if(!in_argument)
2806 in_argument = 1;
2810 else if(*c == '"' && !in_single)
2812 /* Enter or exit double-quote state. */
2813 if(in_double)
2815 in_double = 0;
2817 else
2819 in_double = 1;
2820 if(!in_argument)
2822 in_argument = 1;
2826 else if(isspace((unsigned char) *c))
2828 if(in_argument)
2830 if(in_single || in_double)
2832 /* This space belongs to a quoted argument. */
2833 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2834 &buffer_end, &buffer_size, *c))
2836 failed = 1;
2837 break;
2840 else
2842 /* This argument has been terminated by whitespace. */
2843 if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
2844 &pointer_end, &pointers_size,
2845 local_buffer, &buffer_begin,
2846 &buffer_end, &buffer_size))
2848 failed = 1;
2849 break;
2851 in_argument = 0;
2855 else
2857 /* This character belong to an argument. */
2858 if(!in_argument)
2860 in_argument = 1;
2862 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2863 &buffer_end, &buffer_size, *c))
2865 failed = 1;
2866 break;
2871 /* Finish the last argument. */
2872 if(in_argument)
2874 if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
2875 &pointer_end, &pointers_size,
2876 local_buffer, &buffer_begin,
2877 &buffer_end, &buffer_size))
2879 failed = 1;
2883 /* If we still have memory allocate space for the new command
2884 buffer. */
2885 if(!failed)
2887 kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin;
2888 newCommand = (char**)malloc((size_t)(n+1)*sizeof(char*));
2891 if(newCommand)
2893 /* Copy the arguments into the new command buffer. */
2894 kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin;
2895 memcpy(newCommand, pointer_begin, sizeof(char*)*(size_t)(n));
2896 newCommand[n] = 0;
2898 else
2900 /* Free arguments already allocated. */
2901 while(pointer_end != pointer_begin)
2903 free(*(--pointer_end));
2907 /* Free temporary buffers. */
2908 if(pointer_begin != local_pointers)
2910 free(pointer_begin);
2912 if(buffer_begin != local_buffer)
2914 free(buffer_begin);
2917 /* Return the final command buffer. */
2918 return newCommand;