ENH: fix uppercase version so defines are not upper as well
[cmake.git] / Source / kwsys / ProcessUNIX.c
blobb0deaef2372f4fd5d4f9799bb769ac810c7d969c
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 = (char***)malloc(sizeof(char**) * newNumberOfCommands)))
395 /* Out of memory. */
396 return 0;
399 /* Copy any existing commands into the new array. */
401 int i;
402 for(i=0; i < cp->NumberOfCommands; ++i)
404 newCommands[i] = cp->Commands[i];
408 /* Add the new command. */
409 if(cp->Verbatim)
411 /* In order to run the given command line verbatim we need to
412 parse it. */
413 newCommands[cp->NumberOfCommands] =
414 kwsysProcessParseVerbatimCommand(*command);
415 if(!newCommands[cp->NumberOfCommands])
417 /* Out of memory. */
418 free(newCommands);
419 return 0;
422 else
424 /* Copy each argument string individually. */
425 char const* const* c = command;
426 kwsysProcess_ptrdiff_t n = 0;
427 kwsysProcess_ptrdiff_t i = 0;
428 while(*c++);
429 n = c - command - 1;
430 newCommands[cp->NumberOfCommands] = (char**)malloc((n+1)*sizeof(char*));
431 if(!newCommands[cp->NumberOfCommands])
433 /* Out of memory. */
434 free(newCommands);
435 return 0;
437 for(i=0; i < n; ++i)
439 newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
440 if(!newCommands[cp->NumberOfCommands][i])
442 break;
445 if(i < n)
447 /* Out of memory. */
448 for(;i > 0; --i)
450 free(newCommands[cp->NumberOfCommands][i-1]);
452 free(newCommands);
453 return 0;
455 newCommands[cp->NumberOfCommands][n] = 0;
458 /* Successfully allocated new command array. Free the old array. */
459 free(cp->Commands);
460 cp->Commands = newCommands;
461 cp->NumberOfCommands = newNumberOfCommands;
463 return 1;
466 /*--------------------------------------------------------------------------*/
467 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
469 if(!cp)
471 return;
473 cp->Timeout = timeout;
474 if(cp->Timeout < 0)
476 cp->Timeout = 0;
480 /*--------------------------------------------------------------------------*/
481 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
483 if(!cp)
485 return 0;
487 if(cp->WorkingDirectory == dir)
489 return 1;
491 if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
493 return 1;
495 if(cp->WorkingDirectory)
497 free(cp->WorkingDirectory);
498 cp->WorkingDirectory = 0;
500 if(dir)
502 cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
503 if(!cp->WorkingDirectory)
505 return 0;
507 strcpy(cp->WorkingDirectory, dir);
509 return 1;
512 /*--------------------------------------------------------------------------*/
513 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
515 char** pfile;
516 if(!cp)
518 return 0;
520 switch(prPipe)
522 case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
523 case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
524 case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
525 default: return 0;
527 if(*pfile)
529 free(*pfile);
530 *pfile = 0;
532 if(file)
534 *pfile = malloc(strlen(file)+1);
535 if(!*pfile)
537 return 0;
539 strcpy(*pfile, file);
542 /* If we are redirecting the pipe, do not share it or use a native
543 pipe. */
544 if(*pfile)
546 kwsysProcess_SetPipeNative(cp, prPipe, 0);
547 kwsysProcess_SetPipeShared(cp, prPipe, 0);
549 return 1;
552 /*--------------------------------------------------------------------------*/
553 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
555 if(!cp)
557 return;
560 switch(prPipe)
562 case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
563 case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
564 case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
565 default: return;
568 /* If we are sharing the pipe, do not redirect it to a file or use a
569 native pipe. */
570 if(shared)
572 kwsysProcess_SetPipeFile(cp, prPipe, 0);
573 kwsysProcess_SetPipeNative(cp, prPipe, 0);
577 /*--------------------------------------------------------------------------*/
578 void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
580 int* pPipeNative = 0;
582 if(!cp)
584 return;
587 switch(prPipe)
589 case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
590 case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
591 case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
592 default: return;
595 /* Copy the native pipe descriptors provided. */
596 if(p)
598 pPipeNative[0] = p[0];
599 pPipeNative[1] = p[1];
601 else
603 pPipeNative[0] = -1;
604 pPipeNative[1] = -1;
607 /* If we are using a native pipe, do not share it or redirect it to
608 a file. */
609 if(p)
611 kwsysProcess_SetPipeFile(cp, prPipe, 0);
612 kwsysProcess_SetPipeShared(cp, prPipe, 0);
616 /*--------------------------------------------------------------------------*/
617 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
619 if(!cp)
621 return 0;
624 switch(optionId)
626 case kwsysProcess_Option_Detach: return cp->OptionDetach;
627 case kwsysProcess_Option_Verbatim: return cp->Verbatim;
628 default: return 0;
632 /*--------------------------------------------------------------------------*/
633 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
635 if(!cp)
637 return;
640 switch(optionId)
642 case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
643 case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
644 default: break;
648 /*--------------------------------------------------------------------------*/
649 int kwsysProcess_GetState(kwsysProcess* cp)
651 return cp? cp->State : kwsysProcess_State_Error;
654 /*--------------------------------------------------------------------------*/
655 int kwsysProcess_GetExitException(kwsysProcess* cp)
657 return cp? cp->ExitException : kwsysProcess_Exception_Other;
660 /*--------------------------------------------------------------------------*/
661 int kwsysProcess_GetExitCode(kwsysProcess* cp)
663 return cp? cp->ExitCode : 0;
666 /*--------------------------------------------------------------------------*/
667 int kwsysProcess_GetExitValue(kwsysProcess* cp)
669 return cp? cp->ExitValue : -1;
672 /*--------------------------------------------------------------------------*/
673 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
675 if(!cp)
677 return "Process management structure could not be allocated";
679 else if(cp->State == kwsysProcess_State_Error)
681 return cp->ErrorMessage;
683 return "Success";
686 /*--------------------------------------------------------------------------*/
687 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
689 if(!cp)
691 return "GetExceptionString called with NULL process management structure";
693 else if(cp->State == kwsysProcess_State_Exception)
695 return cp->ExitExceptionString;
697 return "No exception";
700 /*--------------------------------------------------------------------------*/
701 void kwsysProcess_Execute(kwsysProcess* cp)
703 int i;
704 kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
706 /* Do not execute a second copy simultaneously. */
707 if(!cp || cp->State == kwsysProcess_State_Executing)
709 return;
712 /* Initialize the control structure for a new process. */
713 if(!kwsysProcessInitialize(cp))
715 strcpy(cp->ErrorMessage, "Out of memory");
716 cp->State = kwsysProcess_State_Error;
717 return;
720 /* Save the real working directory of this process and change to
721 the working directory for the child processes. This is needed
722 to make pipe file paths evaluate correctly. */
723 if(cp->WorkingDirectory)
725 int r;
726 if(!getcwd(cp->RealWorkingDirectory, cp->RealWorkingDirectoryLength))
728 kwsysProcessCleanup(cp, 1);
729 return;
732 /* Some platforms specify that the chdir call may be
733 interrupted. Repeat the call until it finishes. */
734 while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
735 if(r < 0)
737 kwsysProcessCleanup(cp, 1);
738 return;
742 /* If not running a detached child, add this object to the global
743 set of process objects that wish to be notified when a child
744 exits. */
745 if(!cp->OptionDetach)
747 if(!kwsysProcessesAdd(cp))
749 kwsysProcessCleanup(cp, 1);
750 return;
754 /* Setup the stderr pipe to be shared by all processes. */
756 /* Create the pipe. */
757 int p[2];
758 if(pipe(p) < 0)
760 kwsysProcessCleanup(cp, 1);
761 return;
764 /* Store the pipe. */
765 cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
766 si.StdErr = p[1];
768 /* Set close-on-exec flag on the pipe's ends. */
769 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
770 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
772 kwsysProcessCleanup(cp, 1);
773 kwsysProcessCleanupDescriptor(&si.StdErr);
774 return;
777 /* Set to non-blocking in case select lies, or for the polling
778 implementation. */
779 if(!kwsysProcessSetNonBlocking(p[0]))
781 kwsysProcessCleanup(cp, 1);
782 kwsysProcessCleanupDescriptor(&si.StdErr);
783 return;
787 /* Replace the stderr pipe with a file if requested. In this case
788 the select call will report that stderr is closed immediately. */
789 if(cp->PipeFileSTDERR)
791 if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
793 kwsysProcessCleanup(cp, 1);
794 kwsysProcessCleanupDescriptor(&si.StdErr);
795 return;
799 /* Replace the stderr pipe with the parent's if requested. In this
800 case the select call will report that stderr is closed
801 immediately. */
802 if(cp->PipeSharedSTDERR)
804 kwsysProcessCleanupDescriptor(&si.StdErr);
805 si.StdErr = 2;
808 /* Replace the stderr pipe with the native pipe provided if any. In
809 this case the select call will report that stderr is closed
810 immediately. */
811 if(cp->PipeNativeSTDERR[1] >= 0)
813 if(!kwsysProcessSetupOutputPipeNative(&si.StdErr, cp->PipeNativeSTDERR))
815 kwsysProcessCleanup(cp, 1);
816 kwsysProcessCleanupDescriptor(&si.StdErr);
817 return;
821 /* The timeout period starts now. */
822 cp->StartTime = kwsysProcessTimeGetCurrent();
823 cp->TimeoutTime.tv_sec = -1;
824 cp->TimeoutTime.tv_usec = -1;
826 /* Create the pipeline of processes. */
828 int readEnd = -1;
829 int failed = 0;
830 for(i=0; i < cp->NumberOfCommands; ++i)
832 if(!kwsysProcessCreate(cp, i, &si, &readEnd))
834 failed = 1;
837 /* Set the output pipe of the last process to be non-blocking in
838 case select lies, or for the polling implementation. */
839 if(i == (cp->NumberOfCommands-1) && !kwsysProcessSetNonBlocking(readEnd))
841 failed = 1;
844 if(failed)
846 kwsysProcessCleanup(cp, 1);
848 /* Release resources that may have been allocated for this
849 process before an error occurred. */
850 kwsysProcessCleanupDescriptor(&readEnd);
851 if(si.StdIn != 0)
853 kwsysProcessCleanupDescriptor(&si.StdIn);
855 if(si.StdOut != 1)
857 kwsysProcessCleanupDescriptor(&si.StdOut);
859 if(si.StdErr != 2)
861 kwsysProcessCleanupDescriptor(&si.StdErr);
863 kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
864 kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
865 return;
868 /* Save a handle to the output pipe for the last process. */
869 cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
872 /* The parent process does not need the output pipe write ends. */
873 if(si.StdErr != 2)
875 kwsysProcessCleanupDescriptor(&si.StdErr);
878 /* Restore the working directory. */
879 if(cp->RealWorkingDirectory)
881 /* Some platforms specify that the chdir call may be
882 interrupted. Repeat the call until it finishes. */
883 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
884 free(cp->RealWorkingDirectory);
885 cp->RealWorkingDirectory = 0;
888 /* All the pipes are now open. */
889 cp->PipesLeft = KWSYSPE_PIPE_COUNT;
891 /* The process has now started. */
892 cp->State = kwsysProcess_State_Executing;
893 cp->Detached = cp->OptionDetach;
896 /*--------------------------------------------------------------------------*/
897 kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
899 /* Make sure a detached child process is running. */
900 if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
901 cp->TimeoutExpired || cp->Killed)
903 return;
906 /* Close all the pipes safely. */
907 kwsysProcessClosePipes(cp);
909 /* We will not wait for exit, so cleanup now. */
910 kwsysProcessCleanup(cp, 0);
912 /* The process has been disowned. */
913 cp->State = kwsysProcess_State_Disowned;
916 /*--------------------------------------------------------------------------*/
917 typedef struct kwsysProcessWaitData_s
919 int Expired;
920 int PipeId;
921 int User;
922 double* UserTimeout;
923 kwsysProcessTime TimeoutTime;
924 } kwsysProcessWaitData;
925 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
926 kwsysProcessWaitData* wd);
928 /*--------------------------------------------------------------------------*/
929 int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
930 double* userTimeout)
932 kwsysProcessTime userStartTime = {0, 0};
933 kwsysProcessWaitData wd =
936 kwsysProcess_Pipe_None,
939 {0, 0}
941 wd.UserTimeout = userTimeout;
942 /* Make sure we are executing a process. */
943 if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
944 cp->TimeoutExpired)
946 return kwsysProcess_Pipe_None;
949 /* Record the time at which user timeout period starts. */
950 if(userTimeout)
952 userStartTime = kwsysProcessTimeGetCurrent();
955 /* Calculate the time at which a timeout will expire, and whether it
956 is the user or process timeout. */
957 wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
958 &wd.TimeoutTime);
960 /* Data can only be available when pipes are open. If the process
961 is not running, cp->PipesLeft will be 0. */
962 while(cp->PipesLeft > 0 &&
963 !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
965 /* Update the user timeout. */
966 if(userTimeout)
968 kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
969 kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
970 userStartTime);
971 double d = kwsysProcessTimeToDouble(difference);
972 *userTimeout -= d;
973 if(*userTimeout < 0)
975 *userTimeout = 0;
979 /* Check what happened. */
980 if(wd.PipeId)
982 /* Data are ready on a pipe. */
983 return wd.PipeId;
985 else if(wd.Expired)
987 /* A timeout has expired. */
988 if(wd.User)
990 /* The user timeout has expired. It has no time left. */
991 return kwsysProcess_Pipe_Timeout;
993 else
995 /* The process timeout has expired. Kill the children now. */
996 kwsysProcess_Kill(cp);
997 cp->Killed = 0;
998 cp->TimeoutExpired = 1;
999 return kwsysProcess_Pipe_None;
1002 else
1004 /* No pipes are left open. */
1005 return kwsysProcess_Pipe_None;
1009 /*--------------------------------------------------------------------------*/
1010 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
1011 kwsysProcessWaitData* wd)
1013 int i;
1014 kwsysProcessTimeNative timeoutLength;
1016 #if KWSYSPE_USE_SELECT
1017 int numReady = 0;
1018 int max = -1;
1019 kwsysProcessTimeNative* timeout = 0;
1021 /* Check for any open pipes with data reported ready by the last
1022 call to select. According to "man select_tut" we must deal
1023 with all descriptors reported by a call to select before
1024 passing them to another select call. */
1025 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1027 if(cp->PipeReadEnds[i] >= 0 &&
1028 FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1030 kwsysProcess_ssize_t n;
1032 /* We are handling this pipe now. Remove it from the set. */
1033 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1035 /* The pipe is ready to read without blocking. Keep trying to
1036 read until the operation is not interrupted. */
1037 while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
1038 KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
1039 if(n > 0)
1041 /* We have data on this pipe. */
1042 if(i == KWSYSPE_PIPE_SIGNAL)
1044 /* A child process has terminated. */
1045 kwsysProcessDestroy(cp);
1047 else if(data && length)
1049 /* Report this data. */
1050 *data = cp->PipeBuffer;
1051 *length = n;
1052 switch(i)
1054 case KWSYSPE_PIPE_STDOUT:
1055 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1056 case KWSYSPE_PIPE_STDERR:
1057 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1059 return 1;
1062 else if(n < 0 && errno == EAGAIN)
1064 /* No data are really ready. The select call lied. See the
1065 "man select" page on Linux for cases when this occurs. */
1067 else
1069 /* We are done reading from this pipe. */
1070 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1071 --cp->PipesLeft;
1076 /* If we have data, break early. */
1077 if(wd->PipeId)
1079 return 1;
1082 /* Make sure the set is empty (it should always be empty here
1083 anyway). */
1084 FD_ZERO(&cp->PipeSet);
1086 /* Setup a timeout if required. */
1087 if(wd->TimeoutTime.tv_sec < 0)
1089 timeout = 0;
1091 else
1093 timeout = &timeoutLength;
1095 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
1096 wd->User?wd->UserTimeout:0,
1097 &timeoutLength))
1099 /* Timeout has already expired. */
1100 wd->Expired = 1;
1101 return 1;
1104 /* Add the pipe reading ends that are still open. */
1105 max = -1;
1106 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1108 if(cp->PipeReadEnds[i] >= 0)
1110 FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
1111 if(cp->PipeReadEnds[i] > max)
1113 max = cp->PipeReadEnds[i];
1118 /* Make sure we have a non-empty set. */
1119 if(max < 0)
1121 /* All pipes have closed. Child has terminated. */
1122 return 1;
1125 /* Run select to block until data are available. Repeat call
1126 until it is not interrupted. */
1127 while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
1128 (errno == EINTR));
1130 /* Check result of select. */
1131 if(numReady == 0)
1133 /* Select's timeout expired. */
1134 wd->Expired = 1;
1135 return 1;
1137 else if(numReady < 0)
1139 /* Select returned an error. Leave the error description in the
1140 pipe buffer. */
1141 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1143 /* Kill the children now. */
1144 kwsysProcess_Kill(cp);
1145 cp->Killed = 0;
1146 cp->SelectError = 1;
1149 return 0;
1150 #else
1151 /* Poll pipes for data since we do not have select. */
1152 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1154 if(cp->PipeReadEnds[i] >= 0)
1156 const int fd = cp->PipeReadEnds[i];
1157 int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
1158 if(n > 0)
1160 /* We have data on this pipe. */
1161 if(i == KWSYSPE_PIPE_SIGNAL)
1163 /* A child process has terminated. */
1164 kwsysProcessDestroy(cp);
1166 else if(data && length)
1168 /* Report this data. */
1169 *data = cp->PipeBuffer;
1170 *length = n;
1171 switch(i)
1173 case KWSYSPE_PIPE_STDOUT:
1174 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1175 case KWSYSPE_PIPE_STDERR:
1176 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1179 return 1;
1181 else if (n == 0) /* EOF */
1183 /* We are done reading from this pipe. */
1184 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1185 --cp->PipesLeft;
1187 else if (n < 0) /* error */
1189 if((errno != EINTR) && (errno != EAGAIN))
1191 strncpy(cp->ErrorMessage,strerror(errno),
1192 KWSYSPE_PIPE_BUFFER_SIZE);
1193 /* Kill the children now. */
1194 kwsysProcess_Kill(cp);
1195 cp->Killed = 0;
1196 cp->SelectError = 1;
1197 return 1;
1203 /* If we have data, break early. */
1204 if(wd->PipeId)
1206 return 1;
1209 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
1210 &timeoutLength))
1212 /* Timeout has already expired. */
1213 wd->Expired = 1;
1214 return 1;
1217 if((timeoutLength.tv_sec == 0) && (timeoutLength.tv_usec == 0))
1219 /* Timeout has already expired. */
1220 wd->Expired = 1;
1221 return 1;
1224 /* Sleep a little, try again. */
1226 unsigned int msec = ((timeoutLength.tv_sec * 1000) +
1227 (timeoutLength.tv_usec / 1000));
1228 if (msec > 100000)
1230 msec = 100000; /* do not sleep more than 100 milliseconds at a time */
1232 kwsysProcess_usleep(msec);
1234 return 0;
1235 #endif
1238 /*--------------------------------------------------------------------------*/
1239 int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
1241 int status = 0;
1242 int prPipe = 0;
1244 /* Make sure we are executing a process. */
1245 if(!cp || cp->State != kwsysProcess_State_Executing)
1247 return 1;
1250 /* Wait for all the pipes to close. Ignore all data. */
1251 while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
1253 if(prPipe == kwsysProcess_Pipe_Timeout)
1255 return 0;
1259 /* Check if there was an error in one of the waitpid calls. */
1260 if(cp->State == kwsysProcess_State_Error)
1262 /* The error message is already in its buffer. Tell
1263 kwsysProcessCleanup to not create it. */
1264 kwsysProcessCleanup(cp, 0);
1265 return 1;
1268 /* Check whether the child reported an error invoking the process. */
1269 if(cp->SelectError)
1271 /* The error message is already in its buffer. Tell
1272 kwsysProcessCleanup to not create it. */
1273 kwsysProcessCleanup(cp, 0);
1274 cp->State = kwsysProcess_State_Error;
1275 return 1;
1278 /* Use the status of the last process in the pipeline. */
1279 status = cp->CommandExitCodes[cp->NumberOfCommands-1];
1281 /* Determine the outcome. */
1282 if(cp->Killed)
1284 /* We killed the child. */
1285 cp->State = kwsysProcess_State_Killed;
1287 else if(cp->TimeoutExpired)
1289 /* The timeout expired. */
1290 cp->State = kwsysProcess_State_Expired;
1292 else if(WIFEXITED(status))
1294 /* The child exited normally. */
1295 cp->State = kwsysProcess_State_Exited;
1296 cp->ExitException = kwsysProcess_Exception_None;
1297 cp->ExitCode = status;
1298 cp->ExitValue = (int)WEXITSTATUS(status);
1300 else if(WIFSIGNALED(status))
1302 /* The child received an unhandled signal. */
1303 cp->State = kwsysProcess_State_Exception;
1304 cp->ExitCode = status;
1305 kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
1307 else
1309 /* Error getting the child return code. */
1310 strcpy(cp->ErrorMessage, "Error getting child return code.");
1311 cp->State = kwsysProcess_State_Error;
1314 /* Normal cleanup. */
1315 kwsysProcessCleanup(cp, 0);
1316 return 1;
1319 /*--------------------------------------------------------------------------*/
1320 void kwsysProcess_Kill(kwsysProcess* cp)
1322 int i;
1324 /* Make sure we are executing a process. */
1325 if(!cp || cp->State != kwsysProcess_State_Executing)
1327 return;
1330 /* First close the child exit report pipe write end to avoid causing a
1331 SIGPIPE when the child terminates and our signal handler tries to
1332 report it after we have already closed the read end. */
1333 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1335 #if !defined(__APPLE__)
1336 /* Close all the pipe read ends. Do this before killing the
1337 children because Cygwin has problems killing processes that are
1338 blocking to wait for writing to their output pipes. */
1339 kwsysProcessClosePipes(cp);
1340 #endif
1342 /* Kill the children. */
1343 cp->Killed = 1;
1344 for(i=0; i < cp->NumberOfCommands; ++i)
1346 int status;
1347 if(cp->ForkPIDs[i])
1349 /* Kill the child. */
1350 kwsysProcessKill(cp->ForkPIDs[i]);
1352 /* Reap the child. Keep trying until the call is not
1353 interrupted. */
1354 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
1358 #if defined(__APPLE__)
1359 /* Close all the pipe read ends. Do this after killing the
1360 children because OS X has problems closing pipe read ends whose
1361 pipes are full and still have an open write end. */
1362 kwsysProcessClosePipes(cp);
1363 #endif
1365 cp->CommandsLeft = 0;
1368 /*--------------------------------------------------------------------------*/
1369 /* Initialize a process control structure for kwsysProcess_Execute. */
1370 static int kwsysProcessInitialize(kwsysProcess* cp)
1372 int i;
1373 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1375 cp->PipeReadEnds[i] = -1;
1377 cp->SignalPipe = -1;
1378 cp->SelectError = 0;
1379 cp->StartTime.tv_sec = -1;
1380 cp->StartTime.tv_usec = -1;
1381 cp->TimeoutTime.tv_sec = -1;
1382 cp->TimeoutTime.tv_usec = -1;
1383 cp->TimeoutExpired = 0;
1384 cp->PipesLeft = 0;
1385 cp->CommandsLeft = 0;
1386 #if KWSYSPE_USE_SELECT
1387 FD_ZERO(&cp->PipeSet);
1388 #endif
1389 cp->State = kwsysProcess_State_Starting;
1390 cp->Killed = 0;
1391 cp->ExitException = kwsysProcess_Exception_None;
1392 cp->ExitCode = 1;
1393 cp->ExitValue = 1;
1394 cp->ErrorMessage[0] = 0;
1395 strcpy(cp->ExitExceptionString, "No exception");
1397 if(cp->ForkPIDs)
1399 free(cp->ForkPIDs);
1401 cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*cp->NumberOfCommands);
1402 if(!cp->ForkPIDs)
1404 return 0;
1406 memset(cp->ForkPIDs, 0, sizeof(pid_t)*cp->NumberOfCommands);
1408 if(cp->CommandExitCodes)
1410 free(cp->CommandExitCodes);
1412 cp->CommandExitCodes = (int*)malloc(sizeof(int)*cp->NumberOfCommands);
1413 if(!cp->CommandExitCodes)
1415 return 0;
1417 memset(cp->CommandExitCodes, 0, sizeof(int)*cp->NumberOfCommands);
1419 /* Allocate memory to save the real working directory. */
1420 if ( cp->WorkingDirectory )
1422 #if defined(MAXPATHLEN)
1423 cp->RealWorkingDirectoryLength = MAXPATHLEN;
1424 #elif defined(PATH_MAX)
1425 cp->RealWorkingDirectoryLength = PATH_MAX;
1426 #else
1427 cp->RealWorkingDirectoryLength = 4096;
1428 #endif
1429 cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength);
1430 if(!cp->RealWorkingDirectory)
1432 return 0;
1436 return 1;
1439 /*--------------------------------------------------------------------------*/
1440 /* Free all resources used by the given kwsysProcess instance that were
1441 allocated by kwsysProcess_Execute. */
1442 static void kwsysProcessCleanup(kwsysProcess* cp, int error)
1444 int i;
1446 if(error)
1448 /* We are cleaning up due to an error. Report the error message
1449 if one has not been provided already. */
1450 if(cp->ErrorMessage[0] == 0)
1452 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1455 /* Set the error state. */
1456 cp->State = kwsysProcess_State_Error;
1458 /* Kill any children already started. */
1459 if(cp->ForkPIDs)
1461 int status;
1462 for(i=0; i < cp->NumberOfCommands; ++i)
1464 if(cp->ForkPIDs[i])
1466 /* Kill the child. */
1467 kwsysProcessKill(cp->ForkPIDs[i]);
1469 /* Reap the child. Keep trying until the call is not
1470 interrupted. */
1471 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
1472 (errno == EINTR));
1477 /* Restore the working directory. */
1478 if(cp->RealWorkingDirectory)
1480 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
1484 /* If not creating a detached child, remove this object from the
1485 global set of process objects that wish to be notified when a
1486 child exits. */
1487 if(!cp->OptionDetach)
1489 kwsysProcessesRemove(cp);
1492 /* Free memory. */
1493 if(cp->ForkPIDs)
1495 free(cp->ForkPIDs);
1496 cp->ForkPIDs = 0;
1498 if(cp->RealWorkingDirectory)
1500 free(cp->RealWorkingDirectory);
1501 cp->RealWorkingDirectory = 0;
1504 /* Close pipe handles. */
1505 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1507 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1511 /*--------------------------------------------------------------------------*/
1512 /* Close the given file descriptor if it is open. Reset its value to -1. */
1513 static void kwsysProcessCleanupDescriptor(int* pfd)
1515 if(pfd && *pfd >= 0)
1517 /* Keep trying to close until it is not interrupted by a
1518 * signal. */
1519 while((close(*pfd) < 0) && (errno == EINTR));
1520 *pfd = -1;
1524 /*--------------------------------------------------------------------------*/
1525 static void kwsysProcessClosePipes(kwsysProcess* cp)
1527 int i;
1529 /* Close any pipes that are still open. */
1530 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1532 if(cp->PipeReadEnds[i] >= 0)
1534 #if KWSYSPE_USE_SELECT
1535 /* If the pipe was reported by the last call to select, we must
1536 read from it. This is needed to satisfy the suggestions from
1537 "man select_tut" and is not needed for the polling
1538 implementation. Ignore the data. */
1539 if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1541 /* We are handling this pipe now. Remove it from the set. */
1542 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1544 /* The pipe is ready to read without blocking. Keep trying to
1545 read until the operation is not interrupted. */
1546 while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
1547 KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
1549 #endif
1551 /* We are done reading from this pipe. */
1552 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1553 --cp->PipesLeft;
1558 /*--------------------------------------------------------------------------*/
1559 static int kwsysProcessSetNonBlocking(int fd)
1561 int flags = fcntl(fd, F_GETFL);
1562 if(flags >= 0)
1564 flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
1566 return flags >= 0;
1569 /*--------------------------------------------------------------------------*/
1570 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
1571 kwsysProcessCreateInformation* si, int* readEnd)
1573 /* Setup the process's stdin. */
1574 if(prIndex > 0)
1576 si->StdIn = *readEnd;
1577 *readEnd = 0;
1579 else if(cp->PipeFileSTDIN)
1581 /* Open a file for the child's stdin to read. */
1582 si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
1583 if(si->StdIn < 0)
1585 return 0;
1588 /* Set close-on-exec flag on the pipe's end. */
1589 if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
1591 return 0;
1594 else if(cp->PipeSharedSTDIN)
1596 si->StdIn = 0;
1598 else if(cp->PipeNativeSTDIN[0] >= 0)
1600 si->StdIn = cp->PipeNativeSTDIN[0];
1602 /* Set close-on-exec flag on the pipe's ends. The read end will
1603 be dup2-ed into the stdin descriptor after the fork but before
1604 the exec. */
1605 if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
1606 (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
1608 return 0;
1611 else
1613 si->StdIn = -1;
1616 /* Setup the process's stdout. */
1618 /* Create the pipe. */
1619 int p[2];
1620 if(pipe(p) < 0)
1622 return 0;
1624 *readEnd = p[0];
1625 si->StdOut = p[1];
1627 /* Set close-on-exec flag on the pipe's ends. */
1628 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
1629 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
1631 return 0;
1635 /* Replace the stdout pipe with a file if requested. In this case
1636 the select call will report that stdout is closed immediately. */
1637 if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
1639 if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
1641 return 0;
1645 /* Replace the stdout pipe with the parent's if requested. In this
1646 case the select call will report that stderr is closed
1647 immediately. */
1648 if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
1650 kwsysProcessCleanupDescriptor(&si->StdOut);
1651 si->StdOut = 1;
1654 /* Replace the stdout pipe with the native pipe provided if any. In
1655 this case the select call will report that stdout is closed
1656 immediately. */
1657 if(prIndex == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1] >= 0)
1659 if(!kwsysProcessSetupOutputPipeNative(&si->StdOut, cp->PipeNativeSTDOUT))
1661 return 0;
1665 /* Create the error reporting pipe. */
1666 if(pipe(si->ErrorPipe) < 0)
1668 return 0;
1671 /* Set close-on-exec flag on the error pipe's write end. */
1672 if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
1674 return 0;
1677 /* Fork off a child process. */
1678 cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
1679 if(cp->ForkPIDs[prIndex] < 0)
1681 return 0;
1684 if(cp->ForkPIDs[prIndex] == 0)
1686 /* Close the read end of the error reporting pipe. */
1687 close(si->ErrorPipe[0]);
1689 /* Setup the stdin, stdout, and stderr pipes. */
1690 if(si->StdIn > 0)
1692 dup2(si->StdIn, 0);
1694 else if(si->StdIn < 0)
1696 close(0);
1698 if(si->StdOut != 1)
1700 dup2(si->StdOut, 1);
1702 if(si->StdErr != 2)
1704 dup2(si->StdErr, 2);
1707 /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1708 All other pipe handles will be closed when exec succeeds. */
1709 fcntl(0, F_SETFD, 0);
1710 fcntl(1, F_SETFD, 0);
1711 fcntl(2, F_SETFD, 0);
1713 /* Restore all default signal handlers. */
1714 kwsysProcessRestoreDefaultSignalHandlers();
1716 /* Execute the real process. If successful, this does not return. */
1717 execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
1719 /* Failure. Report error to parent and terminate. */
1720 kwsysProcessChildErrorExit(si->ErrorPipe[1]);
1723 /* A child has been created. */
1724 ++cp->CommandsLeft;
1726 /* We are done with the error reporting pipe write end. */
1727 kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1729 /* Block until the child's exec call succeeds and closes the error
1730 pipe or writes data to the pipe to report an error. */
1732 kwsysProcess_ssize_t total = 0;
1733 kwsysProcess_ssize_t n = 1;
1734 /* Read the entire error message up to the length of our buffer. */
1735 while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
1737 /* Keep trying to read until the operation is not interrupted. */
1738 while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
1739 KWSYSPE_PIPE_BUFFER_SIZE-total)) < 0) &&
1740 (errno == EINTR));
1741 if(n > 0)
1743 total += n;
1747 /* We are done with the error reporting pipe read end. */
1748 kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1750 if(total > 0)
1752 /* The child failed to execute the process. */
1753 return 0;
1757 /* Successfully created this child process. */
1758 if(prIndex > 0 || si->StdIn > 0)
1760 /* The parent process does not need the input pipe read end. */
1761 kwsysProcessCleanupDescriptor(&si->StdIn);
1764 /* The parent process does not need the output pipe write ends. */
1765 if(si->StdOut != 1)
1767 kwsysProcessCleanupDescriptor(&si->StdOut);
1770 return 1;
1773 /*--------------------------------------------------------------------------*/
1774 static void kwsysProcessDestroy(kwsysProcess* cp)
1776 /* A child process has terminated. Reap it if it is one handled by
1777 this object. */
1778 int i;
1779 for(i=0; i < cp->NumberOfCommands; ++i)
1781 if(cp->ForkPIDs[i])
1783 int result;
1784 while(((result = waitpid(cp->ForkPIDs[i],
1785 &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
1786 (errno == EINTR));
1787 if(result > 0)
1789 /* This child has termianted. */
1790 cp->ForkPIDs[i] = 0;
1791 if(--cp->CommandsLeft == 0)
1793 /* All children have terminated. Close the signal pipe
1794 write end so that no more notifications are sent to this
1795 object. */
1796 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1798 /* TODO: Once the children have terminated, switch
1799 WaitForData to use a non-blocking read to get the
1800 rest of the data from the pipe. This is needed when
1801 grandchildren keep the output pipes open. */
1804 else if(result < 0 && cp->State != kwsysProcess_State_Error)
1806 /* Unexpected error. Report the first time this happens. */
1807 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1808 cp->State = kwsysProcess_State_Error;
1814 /*--------------------------------------------------------------------------*/
1815 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
1817 int fout;
1818 if(!name)
1820 return 1;
1823 /* Close the existing descriptor. */
1824 kwsysProcessCleanupDescriptor(p);
1826 /* Open a file for the pipe to write (permissions 644). */
1827 if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC,
1828 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
1830 return 0;
1833 /* Set close-on-exec flag on the pipe's end. */
1834 if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
1836 return 0;
1839 /* Assign the replacement descriptor. */
1840 *p = fout;
1841 return 1;
1844 /*--------------------------------------------------------------------------*/
1845 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
1847 /* Close the existing descriptor. */
1848 kwsysProcessCleanupDescriptor(p);
1850 /* Set close-on-exec flag on the pipe's ends. The proper end will
1851 be dup2-ed into the standard descriptor number after fork but
1852 before exec. */
1853 if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
1854 (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
1856 return 0;
1859 /* Assign the replacement descriptor. */
1860 *p = des[1];
1861 return 1;
1864 /*--------------------------------------------------------------------------*/
1865 /* Get the time at which either the process or user timeout will
1866 expire. Returns 1 if the user timeout is first, and 0 otherwise. */
1867 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
1868 kwsysProcessTime* timeoutTime)
1870 /* The first time this is called, we need to calculate the time at
1871 which the child will timeout. */
1872 if(cp->Timeout && cp->TimeoutTime.tv_sec < 0)
1874 kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
1875 cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
1878 /* Start with process timeout. */
1879 *timeoutTime = cp->TimeoutTime;
1881 /* Check if the user timeout is earlier. */
1882 if(userTimeout)
1884 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1885 kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
1886 kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
1887 userTimeoutLength);
1888 if(timeoutTime->tv_sec < 0 ||
1889 kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
1891 *timeoutTime = userTimeoutTime;
1892 return 1;
1895 return 0;
1898 /*--------------------------------------------------------------------------*/
1899 /* Get the length of time before the given timeout time arrives.
1900 Returns 1 if the time has already arrived, and 0 otherwise. */
1901 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
1902 double* userTimeout,
1903 kwsysProcessTimeNative* timeoutLength)
1905 if(timeoutTime->tv_sec < 0)
1907 /* No timeout time has been requested. */
1908 return 0;
1910 else
1912 /* Calculate the remaining time. */
1913 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1914 kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
1915 currentTime);
1916 if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
1918 /* Caller has explicitly requested a zero timeout. */
1919 timeLeft.tv_sec = 0;
1920 timeLeft.tv_usec = 0;
1923 if(timeLeft.tv_sec < 0)
1925 /* Timeout has already expired. */
1926 return 1;
1928 else
1930 /* There is some time left. */
1931 timeoutLength->tv_sec = timeLeft.tv_sec;
1932 timeoutLength->tv_usec = timeLeft.tv_usec;
1933 return 0;
1938 /*--------------------------------------------------------------------------*/
1939 static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
1941 kwsysProcessTime current;
1942 kwsysProcessTimeNative current_native;
1943 gettimeofday(&current_native, 0);
1944 current.tv_sec = (long)current_native.tv_sec;
1945 current.tv_usec = (long)current_native.tv_usec;
1946 return current;
1949 /*--------------------------------------------------------------------------*/
1950 static double kwsysProcessTimeToDouble(kwsysProcessTime t)
1952 return (double)t.tv_sec + t.tv_usec*0.000001;
1955 /*--------------------------------------------------------------------------*/
1956 static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
1958 kwsysProcessTime t;
1959 t.tv_sec = (long)d;
1960 t.tv_usec = (long)((d-t.tv_sec)*1000000);
1961 return t;
1964 /*--------------------------------------------------------------------------*/
1965 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
1967 return ((in1.tv_sec < in2.tv_sec) ||
1968 ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
1971 /*--------------------------------------------------------------------------*/
1972 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
1974 kwsysProcessTime out;
1975 out.tv_sec = in1.tv_sec + in2.tv_sec;
1976 out.tv_usec = in1.tv_usec + in2.tv_usec;
1977 if(out.tv_usec > 1000000)
1979 out.tv_usec -= 1000000;
1980 out.tv_sec += 1;
1982 return out;
1985 /*--------------------------------------------------------------------------*/
1986 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
1988 kwsysProcessTime out;
1989 out.tv_sec = in1.tv_sec - in2.tv_sec;
1990 out.tv_usec = in1.tv_usec - in2.tv_usec;
1991 if(out.tv_usec < 0)
1993 out.tv_usec += 1000000;
1994 out.tv_sec -= 1;
1996 return out;
1999 /*--------------------------------------------------------------------------*/
2000 #define KWSYSPE_CASE(type, str) \
2001 cp->ExitException = kwsysProcess_Exception_##type; \
2002 strcpy(cp->ExitExceptionString, str)
2003 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
2005 switch (sig)
2007 #ifdef SIGSEGV
2008 case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
2009 #endif
2010 #ifdef SIGBUS
2011 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2012 case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
2013 # endif
2014 #endif
2015 #ifdef SIGFPE
2016 case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
2017 #endif
2018 #ifdef SIGILL
2019 case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
2020 #endif
2021 #ifdef SIGINT
2022 case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
2023 #endif
2024 #ifdef SIGABRT
2025 case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
2026 #endif
2027 #ifdef SIGKILL
2028 case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
2029 #endif
2030 #ifdef SIGTERM
2031 case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
2032 #endif
2033 #ifdef SIGHUP
2034 case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
2035 #endif
2036 #ifdef SIGQUIT
2037 case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
2038 #endif
2039 #ifdef SIGTRAP
2040 case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
2041 #endif
2042 #ifdef SIGIOT
2043 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2044 case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
2045 # endif
2046 #endif
2047 #ifdef SIGUSR1
2048 case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
2049 #endif
2050 #ifdef SIGUSR2
2051 case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
2052 #endif
2053 #ifdef SIGPIPE
2054 case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
2055 #endif
2056 #ifdef SIGALRM
2057 case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
2058 #endif
2059 #ifdef SIGSTKFLT
2060 case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
2061 #endif
2062 #ifdef SIGCHLD
2063 case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
2064 #elif defined(SIGCLD)
2065 case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
2066 #endif
2067 #ifdef SIGCONT
2068 case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
2069 #endif
2070 #ifdef SIGSTOP
2071 case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
2072 #endif
2073 #ifdef SIGTSTP
2074 case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
2075 #endif
2076 #ifdef SIGTTIN
2077 case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
2078 #endif
2079 #ifdef SIGTTOU
2080 case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
2081 #endif
2082 #ifdef SIGURG
2083 case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
2084 #endif
2085 #ifdef SIGXCPU
2086 case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
2087 #endif
2088 #ifdef SIGXFSZ
2089 case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
2090 #endif
2091 #ifdef SIGVTALRM
2092 case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
2093 #endif
2094 #ifdef SIGPROF
2095 case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
2096 #endif
2097 #ifdef SIGWINCH
2098 case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
2099 #endif
2100 #ifdef SIGPOLL
2101 case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
2102 #endif
2103 #ifdef SIGIO
2104 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2105 case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
2106 # endif
2107 #endif
2108 #ifdef SIGPWR
2109 case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
2110 #endif
2111 #ifdef SIGSYS
2112 case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
2113 #endif
2114 #ifdef SIGUNUSED
2115 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2116 case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
2117 # endif
2118 #endif
2119 default:
2120 cp->ExitException = kwsysProcess_Exception_Other;
2121 sprintf(cp->ExitExceptionString, "Signal %d", sig);
2122 break;
2125 #undef KWSYSPE_CASE
2127 /*--------------------------------------------------------------------------*/
2128 /* When the child process encounters an error before its program is
2129 invoked, this is called to report the error to the parent and
2130 exit. */
2131 static void kwsysProcessChildErrorExit(int errorPipe)
2133 /* Construct the error message. */
2134 char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
2135 strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
2137 /* Report the error to the parent through the special pipe. */
2138 write(errorPipe, buffer, strlen(buffer));
2140 /* Terminate without cleanup. */
2141 _exit(1);
2144 /*--------------------------------------------------------------------------*/
2145 /* Restores all signal handlers to their default values. */
2146 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2148 struct sigaction act;
2149 memset(&act, 0, sizeof(struct sigaction));
2150 act.sa_handler = SIG_DFL;
2151 #ifdef SIGHUP
2152 sigaction(SIGHUP, &act, 0);
2153 #endif
2154 #ifdef SIGINT
2155 sigaction(SIGINT, &act, 0);
2156 #endif
2157 #ifdef SIGQUIT
2158 sigaction(SIGQUIT, &act, 0);
2159 #endif
2160 #ifdef SIGILL
2161 sigaction(SIGILL, &act, 0);
2162 #endif
2163 #ifdef SIGTRAP
2164 sigaction(SIGTRAP, &act, 0);
2165 #endif
2166 #ifdef SIGABRT
2167 sigaction(SIGABRT, &act, 0);
2168 #endif
2169 #ifdef SIGIOT
2170 sigaction(SIGIOT, &act, 0);
2171 #endif
2172 #ifdef SIGBUS
2173 sigaction(SIGBUS, &act, 0);
2174 #endif
2175 #ifdef SIGFPE
2176 sigaction(SIGFPE, &act, 0);
2177 #endif
2178 #ifdef SIGUSR1
2179 sigaction(SIGUSR1, &act, 0);
2180 #endif
2181 #ifdef SIGSEGV
2182 sigaction(SIGSEGV, &act, 0);
2183 #endif
2184 #ifdef SIGUSR2
2185 sigaction(SIGUSR2, &act, 0);
2186 #endif
2187 #ifdef SIGPIPE
2188 sigaction(SIGPIPE, &act, 0);
2189 #endif
2190 #ifdef SIGALRM
2191 sigaction(SIGALRM, &act, 0);
2192 #endif
2193 #ifdef SIGTERM
2194 sigaction(SIGTERM, &act, 0);
2195 #endif
2196 #ifdef SIGSTKFLT
2197 sigaction(SIGSTKFLT, &act, 0);
2198 #endif
2199 #ifdef SIGCLD
2200 sigaction(SIGCLD, &act, 0);
2201 #endif
2202 #ifdef SIGCHLD
2203 sigaction(SIGCHLD, &act, 0);
2204 #endif
2205 #ifdef SIGCONT
2206 sigaction(SIGCONT, &act, 0);
2207 #endif
2208 #ifdef SIGTSTP
2209 sigaction(SIGTSTP, &act, 0);
2210 #endif
2211 #ifdef SIGTTIN
2212 sigaction(SIGTTIN, &act, 0);
2213 #endif
2214 #ifdef SIGTTOU
2215 sigaction(SIGTTOU, &act, 0);
2216 #endif
2217 #ifdef SIGURG
2218 sigaction(SIGURG, &act, 0);
2219 #endif
2220 #ifdef SIGXCPU
2221 sigaction(SIGXCPU, &act, 0);
2222 #endif
2223 #ifdef SIGXFSZ
2224 sigaction(SIGXFSZ, &act, 0);
2225 #endif
2226 #ifdef SIGVTALRM
2227 sigaction(SIGVTALRM, &act, 0);
2228 #endif
2229 #ifdef SIGPROF
2230 sigaction(SIGPROF, &act, 0);
2231 #endif
2232 #ifdef SIGWINCH
2233 sigaction(SIGWINCH, &act, 0);
2234 #endif
2235 #ifdef SIGPOLL
2236 sigaction(SIGPOLL, &act, 0);
2237 #endif
2238 #ifdef SIGIO
2239 sigaction(SIGIO, &act, 0);
2240 #endif
2241 #ifdef SIGPWR
2242 sigaction(SIGPWR, &act, 0);
2243 #endif
2244 #ifdef SIGSYS
2245 sigaction(SIGSYS, &act, 0);
2246 #endif
2247 #ifdef SIGUNUSED
2248 sigaction(SIGUNUSED, &act, 0);
2249 #endif
2252 /*--------------------------------------------------------------------------*/
2253 static void kwsysProcessExit(void)
2255 _exit(0);
2258 /*--------------------------------------------------------------------------*/
2259 static pid_t kwsysProcessFork(kwsysProcess* cp,
2260 kwsysProcessCreateInformation* si)
2262 /* Create a detached process if requested. */
2263 if(cp->OptionDetach)
2265 /* Create an intermediate process. */
2266 pid_t middle_pid = fork();
2267 if(middle_pid < 0)
2269 /* Fork failed. Return as if we were not detaching. */
2270 return middle_pid;
2272 else if(middle_pid == 0)
2274 /* This is the intermediate process. Create the real child. */
2275 pid_t child_pid = fork();
2276 if(child_pid == 0)
2278 /* This is the real child process. There is nothing to do here. */
2279 return 0;
2281 else
2283 /* Use the error pipe to report the pid to the real parent. */
2284 while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
2285 (errno == EINTR));
2287 /* Exit without cleanup. The parent holds all resources. */
2288 kwsysProcessExit();
2289 return 0; /* Never reached, but avoids SunCC warning. */
2292 else
2294 /* This is the original parent process. The intermediate
2295 process will use the error pipe to report the pid of the
2296 detached child. */
2297 pid_t child_pid;
2298 int status;
2299 while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
2300 (errno == EINTR));
2302 /* Wait for the intermediate process to exit and clean it up. */
2303 while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
2304 return child_pid;
2307 else
2309 /* Not creating a detached process. Use normal fork. */
2310 return fork();
2314 /*--------------------------------------------------------------------------*/
2315 /* We try to obtain process information by invoking the ps command.
2316 Here we define the command to call on each platform and the
2317 corresponding parsing format string. The parsing format should
2318 have two integers to store: the pid and then the ppid. */
2319 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
2320 # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2321 # define KWSYSPE_PS_FORMAT "%d %d\n"
2322 #elif defined(__hpux) || defined(__sparc) || defined(__sgi) || defined(_AIX)
2323 # define KWSYSPE_PS_COMMAND "ps -ef"
2324 # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
2325 #elif defined(__CYGWIN__)
2326 # define KWSYSPE_PS_COMMAND "ps aux"
2327 # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
2328 #endif
2330 /*--------------------------------------------------------------------------*/
2331 static void kwsysProcessKill(pid_t process_id)
2333 #if defined(__linux__) || defined(__CYGWIN__)
2334 DIR* procdir;
2335 #endif
2337 /* Kill the process now to make sure it does not create more
2338 children. Do not reap it yet so we can identify its existing
2339 children. There is a small race condition here. If the child
2340 forks after we begin looking for children below but before it
2341 receives this kill signal we might miss a child. Also we might
2342 not be able to catch up to a fork bomb. */
2343 kill(process_id, SIGKILL);
2345 /* Kill all children if we can find them. */
2346 #if defined(__linux__) || defined(__CYGWIN__)
2347 /* First try using the /proc filesystem. */
2348 if((procdir = opendir("/proc")) != NULL)
2350 #if defined(MAXPATHLEN)
2351 char fname[MAXPATHLEN];
2352 #elif defined(PATH_MAX)
2353 char fname[PATH_MAX];
2354 #else
2355 char fname[4096];
2356 #endif
2357 char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
2358 struct dirent* d;
2360 /* Each process has a directory in /proc whose name is the pid.
2361 Within this directory is a file called stat that has the
2362 following format:
2364 pid (command line) status ppid ...
2366 We want to get the ppid for all processes. Those that have
2367 process_id as their parent should be recursively killed. */
2368 for(d = readdir(procdir); d; d = readdir(procdir))
2370 int pid;
2371 if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
2373 struct stat finfo;
2374 sprintf(fname, "/proc/%d/stat", pid);
2375 if(stat(fname, &finfo) == 0)
2377 FILE* f = fopen(fname, "r");
2378 if(f)
2380 int nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
2381 buffer[nread] = '\0';
2382 if(nread > 0)
2384 const char* rparen = strrchr(buffer, ')');
2385 int ppid;
2386 if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
2388 if(ppid == process_id)
2390 /* Recursively kill this child and its children. */
2391 kwsysProcessKill(pid);
2395 fclose(f);
2400 closedir(procdir);
2402 else
2403 #endif
2405 #if defined(KWSYSPE_PS_COMMAND)
2406 /* Try running "ps" to get the process information. */
2407 FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
2409 /* Make sure the process started and provided a valid header. */
2410 if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
2412 /* Look for processes whose parent is the process being killed. */
2413 int pid, ppid;
2414 while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
2416 if(ppid == process_id)
2418 /* Recursively kill this child and its children. */
2419 kwsysProcessKill(pid);
2424 /* We are done with the ps process. */
2425 if(ps)
2427 pclose(ps);
2429 #endif
2433 /*--------------------------------------------------------------------------*/
2434 /* Global set of executing processes for use by the signal handler.
2435 This global instance will be zero-initialized by the compiler. */
2436 typedef struct kwsysProcessInstances_s
2438 int Count;
2439 int Size;
2440 kwsysProcess** Processes;
2441 } kwsysProcessInstances;
2442 static kwsysProcessInstances kwsysProcesses;
2444 /* The old SIGCHLD handler. */
2445 static struct sigaction kwsysProcessesOldSigChldAction;
2447 /*--------------------------------------------------------------------------*/
2448 static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
2450 /* Block SIGCHLD while we update the set of pipes to check.
2451 TODO: sigprocmask is undefined for threaded apps. See
2452 pthread_sigmask. */
2453 sigset_t newset;
2454 sigset_t oldset;
2455 sigemptyset(&newset);
2456 sigaddset(&newset, SIGCHLD);
2457 sigprocmask(SIG_BLOCK, &newset, &oldset);
2459 /* Store the new set in that seen by the signal handler. */
2460 kwsysProcesses = *newProcesses;
2462 /* Restore the signal mask to the previous setting. */
2463 sigprocmask(SIG_SETMASK, &oldset, 0);
2466 /*--------------------------------------------------------------------------*/
2467 static int kwsysProcessesAdd(kwsysProcess* cp)
2469 /* Create a pipe through which the signal handler can notify the
2470 given process object that a child has exited. */
2472 /* Create the pipe. */
2473 int p[2];
2474 if(pipe(p) < 0)
2476 return 0;
2479 /* Store the pipes now to be sure they are cleaned up later. */
2480 cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
2481 cp->SignalPipe = p[1];
2483 /* Switch the pipe to non-blocking mode so that reading a byte can
2484 be an atomic test-and-set. */
2485 if(!kwsysProcessSetNonBlocking(p[0]) ||
2486 !kwsysProcessSetNonBlocking(p[1]))
2488 return 0;
2491 /* The children do not need this pipe. Set close-on-exec flag on
2492 the pipe's ends. */
2493 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
2494 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
2496 return 0;
2500 /* Attempt to add the given signal pipe to the signal handler set. */
2503 /* Make sure there is enough space for the new signal pipe. */
2504 kwsysProcessInstances oldProcesses = kwsysProcesses;
2505 kwsysProcessInstances newProcesses = oldProcesses;
2506 if(oldProcesses.Count == oldProcesses.Size)
2508 /* Start with enough space for a small number of process instances
2509 and double the size each time more is needed. */
2510 newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
2512 /* Try allocating the new block of memory. */
2513 if((newProcesses.Processes = ((kwsysProcess**)
2514 malloc(newProcesses.Size*
2515 sizeof(kwsysProcess*)))))
2517 /* Copy the old pipe set to the new memory. */
2518 if(oldProcesses.Count > 0)
2520 memcpy(newProcesses.Processes, oldProcesses.Processes,
2521 (oldProcesses.Count * sizeof(kwsysProcess*)));
2524 else
2526 /* Failed to allocate memory for the new signal pipe set. */
2527 return 0;
2531 /* Append the new signal pipe to the set. */
2532 newProcesses.Processes[newProcesses.Count++] = cp;
2534 /* Store the new set in that seen by the signal handler. */
2535 kwsysProcessesUpdate(&newProcesses);
2537 /* Free the original pipes if new ones were allocated. */
2538 if(newProcesses.Processes != oldProcesses.Processes)
2540 free(oldProcesses.Processes);
2543 /* If this is the first process, enable the signal handler. */
2544 if(newProcesses.Count == 1)
2546 /* Install our handler for SIGCHLD. Repeat call until it is not
2547 interrupted. */
2548 struct sigaction newSigChldAction;
2549 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2550 #if KWSYSPE_USE_SIGINFO
2551 newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
2552 newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2553 # ifdef SA_RESTART
2554 newSigChldAction.sa_flags |= SA_RESTART;
2555 # endif
2556 #else
2557 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2558 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2559 #endif
2560 while((sigaction(SIGCHLD, &newSigChldAction,
2561 &kwsysProcessesOldSigChldAction) < 0) &&
2562 (errno == EINTR));
2566 return 1;
2569 /*--------------------------------------------------------------------------*/
2570 static void kwsysProcessesRemove(kwsysProcess* cp)
2572 /* Attempt to remove the given signal pipe from the signal handler set. */
2574 /* Find the given process in the set. */
2575 kwsysProcessInstances newProcesses = kwsysProcesses;
2576 int i;
2577 for(i=0; i < newProcesses.Count; ++i)
2579 if(newProcesses.Processes[i] == cp)
2581 break;
2584 if(i < newProcesses.Count)
2586 /* Remove the process from the set. */
2587 --newProcesses.Count;
2588 for(; i < newProcesses.Count; ++i)
2590 newProcesses.Processes[i] = newProcesses.Processes[i+1];
2593 /* If this was the last process, disable the signal handler. */
2594 if(newProcesses.Count == 0)
2596 /* Restore the SIGCHLD handler. Repeat call until it is not
2597 interrupted. */
2598 while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
2599 (errno == EINTR));
2601 /* Free the table of process pointers since it is now empty.
2602 This is safe because the signal handler has been removed. */
2603 newProcesses.Size = 0;
2604 free(newProcesses.Processes);
2605 newProcesses.Processes = 0;
2608 /* Store the new set in that seen by the signal handler. */
2609 kwsysProcessesUpdate(&newProcesses);
2613 /* Close the pipe through which the signal handler may have notified
2614 the given process object that a child has exited. */
2615 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
2618 /*--------------------------------------------------------------------------*/
2619 static void kwsysProcessesSignalHandler(int signum
2620 #if KWSYSPE_USE_SIGINFO
2621 , siginfo_t* info, void* ucontext
2622 #endif
2625 (void)signum;
2626 #if KWSYSPE_USE_SIGINFO
2627 (void)info;
2628 (void)ucontext;
2629 #endif
2631 /* Signal all process objects that a child has terminated. */
2633 int i;
2634 for(i=0; i < kwsysProcesses.Count; ++i)
2636 /* Set the pipe in a signalled state. */
2637 char buf = 1;
2638 kwsysProcess* cp = kwsysProcesses.Processes[i];
2639 read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
2640 write(cp->SignalPipe, &buf, 1);
2644 #if !KWSYSPE_USE_SIGINFO
2645 /* Re-Install our handler for SIGCHLD. Repeat call until it is not
2646 interrupted. */
2648 struct sigaction newSigChldAction;
2649 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2650 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2651 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2652 while((sigaction(SIGCHLD, &newSigChldAction,
2653 &kwsysProcessesOldSigChldAction) < 0) &&
2654 (errno == EINTR));
2656 #endif
2659 /*--------------------------------------------------------------------------*/
2660 static int kwsysProcessAppendByte(char* local,
2661 char** begin, char** end,
2662 int* size, char c)
2664 /* Allocate space for the character. */
2665 if((*end - *begin) >= *size)
2667 kwsysProcess_ptrdiff_t length = *end - *begin;
2668 char* newBuffer = (char*)malloc(*size*2);
2669 if(!newBuffer)
2671 return 0;
2673 memcpy(newBuffer, *begin, length*sizeof(char));
2674 if(*begin != local)
2676 free(*begin);
2678 *begin = newBuffer;
2679 *end = *begin + length;
2680 *size *= 2;
2683 /* Store the character. */
2684 *(*end)++ = c;
2685 return 1;
2688 /*--------------------------------------------------------------------------*/
2689 static int kwsysProcessAppendArgument(char** local,
2690 char*** begin, char*** end,
2691 int* size,
2692 char* arg_local,
2693 char** arg_begin, char** arg_end,
2694 int* arg_size)
2696 /* Append a null-terminator to the argument string. */
2697 if(!kwsysProcessAppendByte(arg_local, arg_begin, arg_end, arg_size, '\0'))
2699 return 0;
2702 /* Allocate space for the argument pointer. */
2703 if((*end - *begin) >= *size)
2705 kwsysProcess_ptrdiff_t length = *end - *begin;
2706 char** newPointers = (char**)malloc(*size*2*sizeof(char*));
2707 if(!newPointers)
2709 return 0;
2711 memcpy(newPointers, *begin, length*sizeof(char*));
2712 if(*begin != local)
2714 free(*begin);
2716 *begin = newPointers;
2717 *end = *begin + length;
2718 *size *= 2;
2721 /* Allocate space for the argument string. */
2722 **end = (char*)malloc(*arg_end - *arg_begin);
2723 if(!**end)
2725 return 0;
2728 /* Store the argument in the command array. */
2729 memcpy(**end, *arg_begin, *arg_end - *arg_begin);
2730 ++(*end);
2732 /* Reset the argument to be empty. */
2733 *arg_end = *arg_begin;
2735 return 1;
2738 /*--------------------------------------------------------------------------*/
2739 #define KWSYSPE_LOCAL_BYTE_COUNT 1024
2740 #define KWSYSPE_LOCAL_ARGS_COUNT 32
2741 static char** kwsysProcessParseVerbatimCommand(const char* command)
2743 /* Create a buffer for argument pointers during parsing. */
2744 char* local_pointers[KWSYSPE_LOCAL_ARGS_COUNT];
2745 int pointers_size = KWSYSPE_LOCAL_ARGS_COUNT;
2746 char** pointer_begin = local_pointers;
2747 char** pointer_end = pointer_begin;
2749 /* Create a buffer for argument strings during parsing. */
2750 char local_buffer[KWSYSPE_LOCAL_BYTE_COUNT];
2751 int buffer_size = KWSYSPE_LOCAL_BYTE_COUNT;
2752 char* buffer_begin = local_buffer;
2753 char* buffer_end = buffer_begin;
2755 /* Parse the command string. Try to behave like a UNIX shell. */
2756 char** newCommand = 0;
2757 const char* c = command;
2758 int in_argument = 0;
2759 int in_escape = 0;
2760 int in_single = 0;
2761 int in_double = 0;
2762 int failed = 0;
2763 for(;*c; ++c)
2765 if(in_escape)
2767 /* This character is escaped so do no special handling. */
2768 if(!in_argument)
2770 in_argument = 1;
2772 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2773 &buffer_end, &buffer_size, *c))
2775 failed = 1;
2776 break;
2778 in_escape = 0;
2780 else if(*c == '\\' && !in_single)
2782 /* The next character should be escaped. */
2783 in_escape = 1;
2785 else if(*c == '\'' && !in_double)
2787 /* Enter or exit single-quote state. */
2788 if(in_single)
2790 in_single = 0;
2792 else
2794 in_single = 1;
2795 if(!in_argument)
2797 in_argument = 1;
2801 else if(*c == '"' && !in_single)
2803 /* Enter or exit double-quote state. */
2804 if(in_double)
2806 in_double = 0;
2808 else
2810 in_double = 1;
2811 if(!in_argument)
2813 in_argument = 1;
2817 else if(isspace((unsigned char) *c))
2819 if(in_argument)
2821 if(in_single || in_double)
2823 /* This space belongs to a quoted argument. */
2824 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2825 &buffer_end, &buffer_size, *c))
2827 failed = 1;
2828 break;
2831 else
2833 /* This argument has been terminated by whitespace. */
2834 if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
2835 &pointer_end, &pointers_size,
2836 local_buffer, &buffer_begin,
2837 &buffer_end, &buffer_size))
2839 failed = 1;
2840 break;
2842 in_argument = 0;
2846 else
2848 /* This character belong to an argument. */
2849 if(!in_argument)
2851 in_argument = 1;
2853 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2854 &buffer_end, &buffer_size, *c))
2856 failed = 1;
2857 break;
2862 /* Finish the last argument. */
2863 if(in_argument)
2865 if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
2866 &pointer_end, &pointers_size,
2867 local_buffer, &buffer_begin,
2868 &buffer_end, &buffer_size))
2870 failed = 1;
2874 /* If we still have memory allocate space for the new command
2875 buffer. */
2876 if(!failed)
2878 kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin;
2879 newCommand = (char**)malloc((n+1)*sizeof(char*));
2882 if(newCommand)
2884 /* Copy the arguments into the new command buffer. */
2885 kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin;
2886 memcpy(newCommand, pointer_begin, sizeof(char*)*n);
2887 newCommand[n] = 0;
2889 else
2891 /* Free arguments already allocated. */
2892 while(pointer_end != pointer_begin)
2894 free(*(--pointer_end));
2898 /* Free temporary buffers. */
2899 if(pointer_begin != local_pointers)
2901 free(pointer_begin);
2903 if(buffer_begin != local_buffer)
2905 free(buffer_begin);
2908 /* Return the final command buffer. */
2909 return newCommand;