Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Source / kwsys / ProcessUNIX.c
blob02e35020ed8c29654b686b6e89a0be788232e0e8
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 #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
67 typedef ptrdiff_t kwsysProcess_ptrdiff_t;
68 #else
69 typedef int kwsysProcess_ptrdiff_t;
70 #endif
72 #if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
73 typedef ssize_t kwsysProcess_ssize_t;
74 #else
75 typedef int kwsysProcess_ssize_t;
76 #endif
78 #if defined(__BEOS__) && !defined(__ZETA__)
79 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
80 # include <be/kernel/OS.h>
81 static inline void kwsysProcess_usleep(unsigned int msec)
83 snooze(msec);
85 #else
86 # define kwsysProcess_usleep usleep
87 #endif
90 * BeOS's select() works like WinSock: it's for networking only, and
91 * doesn't work with Unix file handles...socket and file handles are
92 * different namespaces (the same descriptor means different things in
93 * each context!)
95 * So on Unix-like systems where select() is flakey, we'll set the
96 * pipes' file handles to be non-blocking and just poll them directly
97 * without select().
99 #if !defined(__BEOS__)
100 # define KWSYSPE_USE_SELECT 1
101 #endif
103 /* Some platforms do not have siginfo on their signal handlers. */
104 #if defined(SA_SIGINFO) && !defined(__BEOS__)
105 # define KWSYSPE_USE_SIGINFO 1
106 #endif
108 /* The number of pipes for the child's output. The standard stdout
109 and stderr pipes are the first two. One more pipe is used to
110 detect when the child process has terminated. The third pipe is
111 not given to the child process, so it cannot close it until it
112 terminates. */
113 #define KWSYSPE_PIPE_COUNT 3
114 #define KWSYSPE_PIPE_STDOUT 0
115 #define KWSYSPE_PIPE_STDERR 1
116 #define KWSYSPE_PIPE_SIGNAL 2
118 /* The maximum amount to read from a pipe at a time. */
119 #define KWSYSPE_PIPE_BUFFER_SIZE 1024
121 /* Keep track of times using a signed representation. Switch to the
122 native (possibly unsigned) representation only when calling native
123 functions. */
124 typedef struct timeval kwsysProcessTimeNative;
125 typedef struct kwsysProcessTime_s kwsysProcessTime;
126 struct kwsysProcessTime_s
128 long tv_sec;
129 long tv_usec;
132 typedef struct kwsysProcessCreateInformation_s
134 int StdIn;
135 int StdOut;
136 int StdErr;
137 int ErrorPipe[2];
138 } kwsysProcessCreateInformation;
140 /*--------------------------------------------------------------------------*/
141 static int kwsysProcessInitialize(kwsysProcess* cp);
142 static void kwsysProcessCleanup(kwsysProcess* cp, int error);
143 static void kwsysProcessCleanupDescriptor(int* pfd);
144 static void kwsysProcessClosePipes(kwsysProcess* cp);
145 static int kwsysProcessSetNonBlocking(int fd);
146 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
147 kwsysProcessCreateInformation* si, int* readEnd);
148 static void kwsysProcessDestroy(kwsysProcess* cp);
149 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
150 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]);
151 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
152 kwsysProcessTime* timeoutTime);
153 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
154 double* userTimeout,
155 kwsysProcessTimeNative* timeoutLength);
156 static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
157 static double kwsysProcessTimeToDouble(kwsysProcessTime t);
158 static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
159 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
160 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
161 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
162 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
163 static void kwsysProcessChildErrorExit(int errorPipe);
164 static void kwsysProcessRestoreDefaultSignalHandlers(void);
165 static pid_t kwsysProcessFork(kwsysProcess* cp,
166 kwsysProcessCreateInformation* si);
167 static void kwsysProcessKill(pid_t process_id);
168 static int kwsysProcessesAdd(kwsysProcess* cp);
169 static void kwsysProcessesRemove(kwsysProcess* cp);
170 #if KWSYSPE_USE_SIGINFO
171 static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
172 void* ucontext);
173 #else
174 static void kwsysProcessesSignalHandler(int signum);
175 #endif
176 static char** kwsysProcessParseVerbatimCommand(const char* command);
178 /*--------------------------------------------------------------------------*/
179 /* Structure containing data used to implement the child's execution. */
180 struct kwsysProcess_s
182 /* The command lines to execute. */
183 char*** Commands;
184 int NumberOfCommands;
186 /* Descriptors for the read ends of the child's output pipes and
187 the signal pipe. */
188 int PipeReadEnds[KWSYSPE_PIPE_COUNT];
190 /* Write descriptor for child termination signal pipe. */
191 int SignalPipe;
193 /* Buffer for pipe data. */
194 char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
196 /* Process IDs returned by the calls to fork. */
197 pid_t* ForkPIDs;
199 /* Flag for whether the children were terminated by a faild select. */
200 int SelectError;
202 /* The timeout length. */
203 double Timeout;
205 /* The working directory for the process. */
206 char* WorkingDirectory;
208 /* Whether to create the child as a detached process. */
209 int OptionDetach;
211 /* Whether the child was created as a detached process. */
212 int Detached;
214 /* Whether to treat command lines as verbatim. */
215 int Verbatim;
217 /* Time at which the child started. Negative for no timeout. */
218 kwsysProcessTime StartTime;
220 /* Time at which the child will timeout. Negative for no timeout. */
221 kwsysProcessTime TimeoutTime;
223 /* Flag for whether the timeout expired. */
224 int TimeoutExpired;
226 /* The number of pipes left open during execution. */
227 int PipesLeft;
229 #if KWSYSPE_USE_SELECT
230 /* File descriptor set for call to select. */
231 fd_set PipeSet;
232 #endif
234 /* The number of children still executing. */
235 int CommandsLeft;
237 /* The current status of the child process. */
238 int State;
240 /* The exceptional behavior that terminated the child process, if
241 * any. */
242 int ExitException;
244 /* The exit code of the child process. */
245 int ExitCode;
247 /* The exit value of the child process, if any. */
248 int ExitValue;
250 /* Whether the process was killed. */
251 int Killed;
253 /* Buffer for error message in case of failure. */
254 char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
256 /* Description for the ExitException. */
257 char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
259 /* The exit codes of each child process in the pipeline. */
260 int* CommandExitCodes;
262 /* Name of files to which stdin and stdout pipes are attached. */
263 char* PipeFileSTDIN;
264 char* PipeFileSTDOUT;
265 char* PipeFileSTDERR;
267 /* Whether each pipe is shared with the parent process. */
268 int PipeSharedSTDIN;
269 int PipeSharedSTDOUT;
270 int PipeSharedSTDERR;
272 /* Native pipes provided by the user. */
273 int PipeNativeSTDIN[2];
274 int PipeNativeSTDOUT[2];
275 int PipeNativeSTDERR[2];
277 /* The real working directory of this process. */
278 int RealWorkingDirectoryLength;
279 char* RealWorkingDirectory;
282 /*--------------------------------------------------------------------------*/
283 kwsysProcess* kwsysProcess_New(void)
285 /* Allocate a process control structure. */
286 kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
287 if(!cp)
289 return 0;
291 memset(cp, 0, sizeof(kwsysProcess));
293 /* Share stdin with the parent process by default. */
294 cp->PipeSharedSTDIN = 1;
296 /* No native pipes by default. */
297 cp->PipeNativeSTDIN[0] = -1;
298 cp->PipeNativeSTDIN[1] = -1;
299 cp->PipeNativeSTDOUT[0] = -1;
300 cp->PipeNativeSTDOUT[1] = -1;
301 cp->PipeNativeSTDERR[0] = -1;
302 cp->PipeNativeSTDERR[1] = -1;
304 /* Set initial status. */
305 cp->State = kwsysProcess_State_Starting;
307 return cp;
310 /*--------------------------------------------------------------------------*/
311 void kwsysProcess_Delete(kwsysProcess* cp)
313 /* Make sure we have an instance. */
314 if(!cp)
316 return;
319 /* If the process is executing, wait for it to finish. */
320 if(cp->State == kwsysProcess_State_Executing)
322 if(cp->Detached)
324 kwsysProcess_Disown(cp);
326 else
328 kwsysProcess_WaitForExit(cp, 0);
332 /* Free memory. */
333 kwsysProcess_SetCommand(cp, 0);
334 kwsysProcess_SetWorkingDirectory(cp, 0);
335 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
336 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
337 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
338 if(cp->CommandExitCodes)
340 free(cp->CommandExitCodes);
342 free(cp);
345 /*--------------------------------------------------------------------------*/
346 int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
348 int i;
349 if(!cp)
351 return 0;
353 for(i=0; i < cp->NumberOfCommands; ++i)
355 char** c = cp->Commands[i];
356 while(*c)
358 free(*c++);
360 free(cp->Commands[i]);
362 cp->NumberOfCommands = 0;
363 if(cp->Commands)
365 free(cp->Commands);
366 cp->Commands = 0;
368 if(command)
370 return kwsysProcess_AddCommand(cp, command);
372 return 1;
375 /*--------------------------------------------------------------------------*/
376 int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
378 int newNumberOfCommands;
379 char*** newCommands;
381 /* Make sure we have a command to add. */
382 if(!cp || !command || !*command)
384 return 0;
387 /* Allocate a new array for command pointers. */
388 newNumberOfCommands = cp->NumberOfCommands + 1;
389 if(!(newCommands = (char***)malloc(sizeof(char**) * newNumberOfCommands)))
391 /* Out of memory. */
392 return 0;
395 /* Copy any existing commands into the new array. */
397 int i;
398 for(i=0; i < cp->NumberOfCommands; ++i)
400 newCommands[i] = cp->Commands[i];
404 /* Add the new command. */
405 if(cp->Verbatim)
407 /* In order to run the given command line verbatim we need to
408 parse it. */
409 newCommands[cp->NumberOfCommands] =
410 kwsysProcessParseVerbatimCommand(*command);
411 if(!newCommands[cp->NumberOfCommands])
413 /* Out of memory. */
414 free(newCommands);
415 return 0;
418 else
420 /* Copy each argument string individually. */
421 char const* const* c = command;
422 kwsysProcess_ptrdiff_t n = 0;
423 kwsysProcess_ptrdiff_t i = 0;
424 while(*c++);
425 n = c - command - 1;
426 newCommands[cp->NumberOfCommands] = (char**)malloc((n+1)*sizeof(char*));
427 if(!newCommands[cp->NumberOfCommands])
429 /* Out of memory. */
430 free(newCommands);
431 return 0;
433 for(i=0; i < n; ++i)
435 newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
436 if(!newCommands[cp->NumberOfCommands][i])
438 break;
441 if(i < n)
443 /* Out of memory. */
444 for(;i > 0; --i)
446 free(newCommands[cp->NumberOfCommands][i-1]);
448 free(newCommands);
449 return 0;
451 newCommands[cp->NumberOfCommands][n] = 0;
454 /* Successfully allocated new command array. Free the old array. */
455 free(cp->Commands);
456 cp->Commands = newCommands;
457 cp->NumberOfCommands = newNumberOfCommands;
459 return 1;
462 /*--------------------------------------------------------------------------*/
463 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
465 if(!cp)
467 return;
469 cp->Timeout = timeout;
470 if(cp->Timeout < 0)
472 cp->Timeout = 0;
476 /*--------------------------------------------------------------------------*/
477 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
479 if(!cp)
481 return 0;
483 if(cp->WorkingDirectory == dir)
485 return 1;
487 if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
489 return 1;
491 if(cp->WorkingDirectory)
493 free(cp->WorkingDirectory);
494 cp->WorkingDirectory = 0;
496 if(dir)
498 cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
499 if(!cp->WorkingDirectory)
501 return 0;
503 strcpy(cp->WorkingDirectory, dir);
505 return 1;
508 /*--------------------------------------------------------------------------*/
509 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
511 char** pfile;
512 if(!cp)
514 return 0;
516 switch(prPipe)
518 case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
519 case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
520 case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
521 default: return 0;
523 if(*pfile)
525 free(*pfile);
526 *pfile = 0;
528 if(file)
530 *pfile = malloc(strlen(file)+1);
531 if(!*pfile)
533 return 0;
535 strcpy(*pfile, file);
538 /* If we are redirecting the pipe, do not share it or use a native
539 pipe. */
540 if(*pfile)
542 kwsysProcess_SetPipeNative(cp, prPipe, 0);
543 kwsysProcess_SetPipeShared(cp, prPipe, 0);
545 return 1;
548 /*--------------------------------------------------------------------------*/
549 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
551 if(!cp)
553 return;
556 switch(prPipe)
558 case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
559 case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
560 case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
561 default: return;
564 /* If we are sharing the pipe, do not redirect it to a file or use a
565 native pipe. */
566 if(shared)
568 kwsysProcess_SetPipeFile(cp, prPipe, 0);
569 kwsysProcess_SetPipeNative(cp, prPipe, 0);
573 /*--------------------------------------------------------------------------*/
574 void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
576 int* pPipeNative = 0;
578 if(!cp)
580 return;
583 switch(prPipe)
585 case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
586 case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
587 case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
588 default: return;
591 /* Copy the native pipe descriptors provided. */
592 if(p)
594 pPipeNative[0] = p[0];
595 pPipeNative[1] = p[1];
597 else
599 pPipeNative[0] = -1;
600 pPipeNative[1] = -1;
603 /* If we are using a native pipe, do not share it or redirect it to
604 a file. */
605 if(p)
607 kwsysProcess_SetPipeFile(cp, prPipe, 0);
608 kwsysProcess_SetPipeShared(cp, prPipe, 0);
612 /*--------------------------------------------------------------------------*/
613 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
615 if(!cp)
617 return 0;
620 switch(optionId)
622 case kwsysProcess_Option_Detach: return cp->OptionDetach;
623 case kwsysProcess_Option_Verbatim: return cp->Verbatim;
624 default: return 0;
628 /*--------------------------------------------------------------------------*/
629 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
631 if(!cp)
633 return;
636 switch(optionId)
638 case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
639 case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
640 default: break;
644 /*--------------------------------------------------------------------------*/
645 int kwsysProcess_GetState(kwsysProcess* cp)
647 return cp? cp->State : kwsysProcess_State_Error;
650 /*--------------------------------------------------------------------------*/
651 int kwsysProcess_GetExitException(kwsysProcess* cp)
653 return cp? cp->ExitException : kwsysProcess_Exception_Other;
656 /*--------------------------------------------------------------------------*/
657 int kwsysProcess_GetExitCode(kwsysProcess* cp)
659 return cp? cp->ExitCode : 0;
662 /*--------------------------------------------------------------------------*/
663 int kwsysProcess_GetExitValue(kwsysProcess* cp)
665 return cp? cp->ExitValue : -1;
668 /*--------------------------------------------------------------------------*/
669 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
671 if(!cp)
673 return "Process management structure could not be allocated";
675 else if(cp->State == kwsysProcess_State_Error)
677 return cp->ErrorMessage;
679 return "Success";
682 /*--------------------------------------------------------------------------*/
683 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
685 if(!cp)
687 return "GetExceptionString called with NULL process management structure";
689 else if(cp->State == kwsysProcess_State_Exception)
691 return cp->ExitExceptionString;
693 return "No exception";
696 /*--------------------------------------------------------------------------*/
697 void kwsysProcess_Execute(kwsysProcess* cp)
699 int i;
700 kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
702 /* Do not execute a second copy simultaneously. */
703 if(!cp || cp->State == kwsysProcess_State_Executing)
705 return;
708 /* Initialize the control structure for a new process. */
709 if(!kwsysProcessInitialize(cp))
711 strcpy(cp->ErrorMessage, "Out of memory");
712 cp->State = kwsysProcess_State_Error;
713 return;
716 /* Save the real working directory of this process and change to
717 the working directory for the child processes. This is needed
718 to make pipe file paths evaluate correctly. */
719 if(cp->WorkingDirectory)
721 int r;
722 if(!getcwd(cp->RealWorkingDirectory, cp->RealWorkingDirectoryLength))
724 kwsysProcessCleanup(cp, 1);
725 return;
728 /* Some platforms specify that the chdir call may be
729 interrupted. Repeat the call until it finishes. */
730 while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
731 if(r < 0)
733 kwsysProcessCleanup(cp, 1);
734 return;
738 /* If not running a detached child, add this object to the global
739 set of process objects that wish to be notified when a child
740 exits. */
741 if(!cp->OptionDetach)
743 if(!kwsysProcessesAdd(cp))
745 kwsysProcessCleanup(cp, 1);
746 return;
750 /* Setup the stderr pipe to be shared by all processes. */
752 /* Create the pipe. */
753 int p[2];
754 if(pipe(p) < 0)
756 kwsysProcessCleanup(cp, 1);
757 return;
760 /* Store the pipe. */
761 cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
762 si.StdErr = p[1];
764 /* Set close-on-exec flag on the pipe's ends. */
765 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
766 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
768 kwsysProcessCleanup(cp, 1);
769 kwsysProcessCleanupDescriptor(&si.StdErr);
770 return;
773 #if !KWSYSPE_USE_SELECT
774 if(!kwsysProcessSetNonBlocking(p[0]))
776 kwsysProcessCleanup(cp, 1);
777 kwsysProcessCleanupDescriptor(&si.StdErr);
778 return;
780 #endif
783 /* Replace the stderr pipe with a file if requested. In this case
784 the select call will report that stderr is closed immediately. */
785 if(cp->PipeFileSTDERR)
787 if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
789 kwsysProcessCleanup(cp, 1);
790 kwsysProcessCleanupDescriptor(&si.StdErr);
791 return;
795 /* Replace the stderr pipe with the parent's if requested. In this
796 case the select call will report that stderr is closed
797 immediately. */
798 if(cp->PipeSharedSTDERR)
800 kwsysProcessCleanupDescriptor(&si.StdErr);
801 si.StdErr = 2;
804 /* Replace the stderr pipe with the native pipe provided if any. In
805 this case the select call will report that stderr is closed
806 immediately. */
807 if(cp->PipeNativeSTDERR[1] >= 0)
809 if(!kwsysProcessSetupOutputPipeNative(&si.StdErr, cp->PipeNativeSTDERR))
811 kwsysProcessCleanup(cp, 1);
812 kwsysProcessCleanupDescriptor(&si.StdErr);
813 return;
817 /* The timeout period starts now. */
818 cp->StartTime = kwsysProcessTimeGetCurrent();
819 cp->TimeoutTime.tv_sec = -1;
820 cp->TimeoutTime.tv_usec = -1;
822 /* Create the pipeline of processes. */
824 int readEnd = -1;
825 int failed = 0;
826 for(i=0; i < cp->NumberOfCommands; ++i)
828 if(!kwsysProcessCreate(cp, i, &si, &readEnd))
830 failed = 1;
833 #if !KWSYSPE_USE_SELECT
834 /* Set the output pipe of the last process to be non-blocking so
835 we can poll it. */
836 if(i == cp->NumberOfCommands-1 && !kwsysProcessSetNonBlocking(readEnd))
838 failed = 1;
840 #endif
842 if(failed)
844 kwsysProcessCleanup(cp, 1);
846 /* Release resources that may have been allocated for this
847 process before an error occurred. */
848 kwsysProcessCleanupDescriptor(&readEnd);
849 if(si.StdIn != 0)
851 kwsysProcessCleanupDescriptor(&si.StdIn);
853 if(si.StdOut != 1)
855 kwsysProcessCleanupDescriptor(&si.StdOut);
857 if(si.StdErr != 2)
859 kwsysProcessCleanupDescriptor(&si.StdErr);
861 kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
862 kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
863 return;
866 /* Save a handle to the output pipe for the last process. */
867 cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
870 /* The parent process does not need the output pipe write ends. */
871 if(si.StdErr != 2)
873 kwsysProcessCleanupDescriptor(&si.StdErr);
876 /* Restore the working directory. */
877 if(cp->RealWorkingDirectory)
879 /* Some platforms specify that the chdir call may be
880 interrupted. Repeat the call until it finishes. */
881 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
882 free(cp->RealWorkingDirectory);
883 cp->RealWorkingDirectory = 0;
886 /* All the pipes are now open. */
887 cp->PipesLeft = KWSYSPE_PIPE_COUNT;
889 /* The process has now started. */
890 cp->State = kwsysProcess_State_Executing;
891 cp->Detached = cp->OptionDetach;
894 /*--------------------------------------------------------------------------*/
895 kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
897 /* Make sure a detached child process is running. */
898 if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
899 cp->TimeoutExpired || cp->Killed)
901 return;
904 /* Close all the pipes safely. */
905 kwsysProcessClosePipes(cp);
907 /* We will not wait for exit, so cleanup now. */
908 kwsysProcessCleanup(cp, 0);
910 /* The process has been disowned. */
911 cp->State = kwsysProcess_State_Disowned;
914 /*--------------------------------------------------------------------------*/
915 typedef struct kwsysProcessWaitData_s
917 int Expired;
918 int PipeId;
919 int User;
920 double* UserTimeout;
921 kwsysProcessTime TimeoutTime;
922 } kwsysProcessWaitData;
923 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
924 kwsysProcessWaitData* wd);
926 /*--------------------------------------------------------------------------*/
927 int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
928 double* userTimeout)
930 kwsysProcessTime userStartTime = {0, 0};
931 kwsysProcessWaitData wd =
934 kwsysProcess_Pipe_None,
937 {0, 0}
939 wd.UserTimeout = userTimeout;
940 /* Make sure we are executing a process. */
941 if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
942 cp->TimeoutExpired)
944 return kwsysProcess_Pipe_None;
947 /* Record the time at which user timeout period starts. */
948 if(userTimeout)
950 userStartTime = kwsysProcessTimeGetCurrent();
953 /* Calculate the time at which a timeout will expire, and whether it
954 is the user or process timeout. */
955 wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
956 &wd.TimeoutTime);
958 /* Data can only be available when pipes are open. If the process
959 is not running, cp->PipesLeft will be 0. */
960 while(cp->PipesLeft > 0 &&
961 !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
963 /* Update the user timeout. */
964 if(userTimeout)
966 kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
967 kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
968 userStartTime);
969 double d = kwsysProcessTimeToDouble(difference);
970 *userTimeout -= d;
971 if(*userTimeout < 0)
973 *userTimeout = 0;
977 /* Check what happened. */
978 if(wd.PipeId)
980 /* Data are ready on a pipe. */
981 return wd.PipeId;
983 else if(wd.Expired)
985 /* A timeout has expired. */
986 if(wd.User)
988 /* The user timeout has expired. It has no time left. */
989 return kwsysProcess_Pipe_Timeout;
991 else
993 /* The process timeout has expired. Kill the children now. */
994 kwsysProcess_Kill(cp);
995 cp->Killed = 0;
996 cp->TimeoutExpired = 1;
997 return kwsysProcess_Pipe_None;
1000 else
1002 /* No pipes are left open. */
1003 return kwsysProcess_Pipe_None;
1007 /*--------------------------------------------------------------------------*/
1008 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
1009 kwsysProcessWaitData* wd)
1011 int i;
1012 kwsysProcessTimeNative timeoutLength;
1014 #if KWSYSPE_USE_SELECT
1015 int numReady = 0;
1016 int max = -1;
1017 kwsysProcessTimeNative* timeout = 0;
1019 /* Check for any open pipes with data reported ready by the last
1020 call to select. According to "man select_tut" we must deal
1021 with all descriptors reported by a call to select before
1022 passing them to another select call. */
1023 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1025 if(cp->PipeReadEnds[i] >= 0 &&
1026 FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1028 kwsysProcess_ssize_t n;
1030 /* We are handling this pipe now. Remove it from the set. */
1031 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1033 /* The pipe is ready to read without blocking. Keep trying to
1034 read until the operation is not interrupted. */
1035 while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
1036 KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
1037 if(n > 0)
1039 /* We have data on this pipe. */
1040 if(i == KWSYSPE_PIPE_SIGNAL)
1042 /* A child process has terminated. */
1043 kwsysProcessDestroy(cp);
1045 else if(data && length)
1047 /* Report this data. */
1048 *data = cp->PipeBuffer;
1049 *length = n;
1050 switch(i)
1052 case KWSYSPE_PIPE_STDOUT:
1053 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1054 case KWSYSPE_PIPE_STDERR:
1055 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1057 return 1;
1060 else
1062 /* We are done reading from this pipe. */
1063 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1064 --cp->PipesLeft;
1069 /* If we have data, break early. */
1070 if(wd->PipeId)
1072 return 1;
1075 /* Make sure the set is empty (it should always be empty here
1076 anyway). */
1077 FD_ZERO(&cp->PipeSet);
1079 /* Setup a timeout if required. */
1080 if(wd->TimeoutTime.tv_sec < 0)
1082 timeout = 0;
1084 else
1086 timeout = &timeoutLength;
1088 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
1089 wd->User?wd->UserTimeout:0,
1090 &timeoutLength))
1092 /* Timeout has already expired. */
1093 wd->Expired = 1;
1094 return 1;
1097 /* Add the pipe reading ends that are still open. */
1098 max = -1;
1099 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1101 if(cp->PipeReadEnds[i] >= 0)
1103 FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
1104 if(cp->PipeReadEnds[i] > max)
1106 max = cp->PipeReadEnds[i];
1111 /* Make sure we have a non-empty set. */
1112 if(max < 0)
1114 /* All pipes have closed. Child has terminated. */
1115 return 1;
1118 /* Run select to block until data are available. Repeat call
1119 until it is not interrupted. */
1120 while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
1121 (errno == EINTR));
1123 /* Check result of select. */
1124 if(numReady == 0)
1126 /* Select's timeout expired. */
1127 wd->Expired = 1;
1128 return 1;
1130 else if(numReady < 0)
1132 /* Select returned an error. Leave the error description in the
1133 pipe buffer. */
1134 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1136 /* Kill the children now. */
1137 kwsysProcess_Kill(cp);
1138 cp->Killed = 0;
1139 cp->SelectError = 1;
1142 return 0;
1143 #else
1144 /* Poll pipes for data since we do not have select. */
1145 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1147 if(cp->PipeReadEnds[i] >= 0)
1149 const int fd = cp->PipeReadEnds[i];
1150 int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
1151 if(n > 0)
1153 /* We have data on this pipe. */
1154 if(i == KWSYSPE_PIPE_SIGNAL)
1156 /* A child process has terminated. */
1157 kwsysProcessDestroy(cp);
1159 else if(data && length)
1161 /* Report this data. */
1162 *data = cp->PipeBuffer;
1163 *length = n;
1164 switch(i)
1166 case KWSYSPE_PIPE_STDOUT:
1167 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1168 case KWSYSPE_PIPE_STDERR:
1169 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1172 return 1;
1174 else if (n == 0) /* EOF */
1176 /* We are done reading from this pipe. */
1177 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1178 --cp->PipesLeft;
1180 else if (n < 0) /* error */
1182 if((errno != EINTR) && (errno != EAGAIN))
1184 strncpy(cp->ErrorMessage,strerror(errno),
1185 KWSYSPE_PIPE_BUFFER_SIZE);
1186 /* Kill the children now. */
1187 kwsysProcess_Kill(cp);
1188 cp->Killed = 0;
1189 cp->SelectError = 1;
1190 return 1;
1196 /* If we have data, break early. */
1197 if(wd->PipeId)
1199 return 1;
1202 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
1203 &timeoutLength))
1205 /* Timeout has already expired. */
1206 wd->Expired = 1;
1207 return 1;
1210 if((timeoutLength.tv_sec == 0) && (timeoutLength.tv_usec == 0))
1212 /* Timeout has already expired. */
1213 wd->Expired = 1;
1214 return 1;
1217 /* Sleep a little, try again. */
1219 unsigned int msec = ((timeoutLength.tv_sec * 1000) +
1220 (timeoutLength.tv_usec / 1000));
1221 if (msec > 100000)
1223 msec = 100000; /* do not sleep more than 100 milliseconds at a time */
1225 kwsysProcess_usleep(msec);
1227 return 0;
1228 #endif
1231 /*--------------------------------------------------------------------------*/
1232 int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
1234 int status = 0;
1235 int prPipe = 0;
1237 /* Make sure we are executing a process. */
1238 if(!cp || cp->State != kwsysProcess_State_Executing)
1240 return 1;
1243 /* Wait for all the pipes to close. Ignore all data. */
1244 while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
1246 if(prPipe == kwsysProcess_Pipe_Timeout)
1248 return 0;
1252 /* Check if there was an error in one of the waitpid calls. */
1253 if(cp->State == kwsysProcess_State_Error)
1255 /* The error message is already in its buffer. Tell
1256 kwsysProcessCleanup to not create it. */
1257 kwsysProcessCleanup(cp, 0);
1258 return 1;
1261 /* Check whether the child reported an error invoking the process. */
1262 if(cp->SelectError)
1264 /* The error message is already in its buffer. Tell
1265 kwsysProcessCleanup to not create it. */
1266 kwsysProcessCleanup(cp, 0);
1267 cp->State = kwsysProcess_State_Error;
1268 return 1;
1271 /* Use the status of the last process in the pipeline. */
1272 status = cp->CommandExitCodes[cp->NumberOfCommands-1];
1274 /* Determine the outcome. */
1275 if(cp->Killed)
1277 /* We killed the child. */
1278 cp->State = kwsysProcess_State_Killed;
1280 else if(cp->TimeoutExpired)
1282 /* The timeout expired. */
1283 cp->State = kwsysProcess_State_Expired;
1285 else if(WIFEXITED(status))
1287 /* The child exited normally. */
1288 cp->State = kwsysProcess_State_Exited;
1289 cp->ExitException = kwsysProcess_Exception_None;
1290 cp->ExitCode = status;
1291 cp->ExitValue = (int)WEXITSTATUS(status);
1293 else if(WIFSIGNALED(status))
1295 /* The child received an unhandled signal. */
1296 cp->State = kwsysProcess_State_Exception;
1297 cp->ExitCode = status;
1298 kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
1300 else
1302 /* Error getting the child return code. */
1303 strcpy(cp->ErrorMessage, "Error getting child return code.");
1304 cp->State = kwsysProcess_State_Error;
1307 /* Normal cleanup. */
1308 kwsysProcessCleanup(cp, 0);
1309 return 1;
1312 /*--------------------------------------------------------------------------*/
1313 void kwsysProcess_Kill(kwsysProcess* cp)
1315 int i;
1317 /* Make sure we are executing a process. */
1318 if(!cp || cp->State != kwsysProcess_State_Executing)
1320 return;
1323 /* First close the child exit report pipe write end to avoid causing a
1324 SIGPIPE when the child terminates and our signal handler tries to
1325 report it after we have already closed the read end. */
1326 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1328 #if !defined(__APPLE__)
1329 /* Close all the pipe read ends. Do this before killing the
1330 children because Cygwin has problems killing processes that are
1331 blocking to wait for writing to their output pipes. */
1332 kwsysProcessClosePipes(cp);
1333 #endif
1335 /* Kill the children. */
1336 cp->Killed = 1;
1337 for(i=0; i < cp->NumberOfCommands; ++i)
1339 int status;
1340 if(cp->ForkPIDs[i])
1342 /* Kill the child. */
1343 kwsysProcessKill(cp->ForkPIDs[i]);
1345 /* Reap the child. Keep trying until the call is not
1346 interrupted. */
1347 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
1351 #if defined(__APPLE__)
1352 /* Close all the pipe read ends. Do this after killing the
1353 children because OS X has problems closing pipe read ends whose
1354 pipes are full and still have an open write end. */
1355 kwsysProcessClosePipes(cp);
1356 #endif
1358 cp->CommandsLeft = 0;
1361 /*--------------------------------------------------------------------------*/
1362 /* Initialize a process control structure for kwsysProcess_Execute. */
1363 static int kwsysProcessInitialize(kwsysProcess* cp)
1365 int i;
1366 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1368 cp->PipeReadEnds[i] = -1;
1370 cp->SignalPipe = -1;
1371 cp->SelectError = 0;
1372 cp->StartTime.tv_sec = -1;
1373 cp->StartTime.tv_usec = -1;
1374 cp->TimeoutTime.tv_sec = -1;
1375 cp->TimeoutTime.tv_usec = -1;
1376 cp->TimeoutExpired = 0;
1377 cp->PipesLeft = 0;
1378 cp->CommandsLeft = 0;
1379 #if KWSYSPE_USE_SELECT
1380 FD_ZERO(&cp->PipeSet);
1381 #endif
1382 cp->State = kwsysProcess_State_Starting;
1383 cp->Killed = 0;
1384 cp->ExitException = kwsysProcess_Exception_None;
1385 cp->ExitCode = 1;
1386 cp->ExitValue = 1;
1387 cp->ErrorMessage[0] = 0;
1388 strcpy(cp->ExitExceptionString, "No exception");
1390 if(cp->ForkPIDs)
1392 free(cp->ForkPIDs);
1394 cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*cp->NumberOfCommands);
1395 if(!cp->ForkPIDs)
1397 return 0;
1399 memset(cp->ForkPIDs, 0, sizeof(pid_t)*cp->NumberOfCommands);
1401 if(cp->CommandExitCodes)
1403 free(cp->CommandExitCodes);
1405 cp->CommandExitCodes = (int*)malloc(sizeof(int)*cp->NumberOfCommands);
1406 if(!cp->CommandExitCodes)
1408 return 0;
1410 memset(cp->CommandExitCodes, 0, sizeof(int)*cp->NumberOfCommands);
1412 /* Allocate memory to save the real working directory. */
1413 if ( cp->WorkingDirectory )
1415 #if defined(MAXPATHLEN)
1416 cp->RealWorkingDirectoryLength = MAXPATHLEN;
1417 #elif defined(PATH_MAX)
1418 cp->RealWorkingDirectoryLength = PATH_MAX;
1419 #else
1420 cp->RealWorkingDirectoryLength = 4096;
1421 #endif
1422 cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength);
1423 if(!cp->RealWorkingDirectory)
1425 return 0;
1429 return 1;
1432 /*--------------------------------------------------------------------------*/
1433 /* Free all resources used by the given kwsysProcess instance that were
1434 allocated by kwsysProcess_Execute. */
1435 static void kwsysProcessCleanup(kwsysProcess* cp, int error)
1437 int i;
1439 if(error)
1441 /* We are cleaning up due to an error. Report the error message
1442 if one has not been provided already. */
1443 if(cp->ErrorMessage[0] == 0)
1445 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1448 /* Set the error state. */
1449 cp->State = kwsysProcess_State_Error;
1451 /* Kill any children already started. */
1452 if(cp->ForkPIDs)
1454 int status;
1455 for(i=0; i < cp->NumberOfCommands; ++i)
1457 if(cp->ForkPIDs[i])
1459 /* Kill the child. */
1460 kwsysProcessKill(cp->ForkPIDs[i]);
1462 /* Reap the child. Keep trying until the call is not
1463 interrupted. */
1464 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
1465 (errno == EINTR));
1470 /* Restore the working directory. */
1471 if(cp->RealWorkingDirectory)
1473 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
1477 /* If not creating a detached child, remove this object from the
1478 global set of process objects that wish to be notified when a
1479 child exits. */
1480 if(!cp->OptionDetach)
1482 kwsysProcessesRemove(cp);
1485 /* Free memory. */
1486 if(cp->ForkPIDs)
1488 free(cp->ForkPIDs);
1489 cp->ForkPIDs = 0;
1491 if(cp->RealWorkingDirectory)
1493 free(cp->RealWorkingDirectory);
1494 cp->RealWorkingDirectory = 0;
1497 /* Close pipe handles. */
1498 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1500 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1504 /*--------------------------------------------------------------------------*/
1505 /* Close the given file descriptor if it is open. Reset its value to -1. */
1506 static void kwsysProcessCleanupDescriptor(int* pfd)
1508 if(pfd && *pfd >= 0)
1510 /* Keep trying to close until it is not interrupted by a
1511 * signal. */
1512 while((close(*pfd) < 0) && (errno == EINTR));
1513 *pfd = -1;
1517 /*--------------------------------------------------------------------------*/
1518 static void kwsysProcessClosePipes(kwsysProcess* cp)
1520 int i;
1522 /* Close any pipes that are still open. */
1523 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1525 if(cp->PipeReadEnds[i] >= 0)
1527 #if KWSYSPE_USE_SELECT
1528 /* If the pipe was reported by the last call to select, we must
1529 read from it. This is needed to satisfy the suggestions from
1530 "man select_tut" and is not needed for the polling
1531 implementation. Ignore the data. */
1532 if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1534 /* We are handling this pipe now. Remove it from the set. */
1535 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1537 /* The pipe is ready to read without blocking. Keep trying to
1538 read until the operation is not interrupted. */
1539 while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
1540 KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
1542 #endif
1544 /* We are done reading from this pipe. */
1545 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1546 --cp->PipesLeft;
1551 /*--------------------------------------------------------------------------*/
1552 static int kwsysProcessSetNonBlocking(int fd)
1554 int flags = fcntl(fd, F_GETFL);
1555 if(flags >= 0)
1557 flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
1559 return flags >= 0;
1562 /*--------------------------------------------------------------------------*/
1563 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
1564 kwsysProcessCreateInformation* si, int* readEnd)
1566 /* Setup the process's stdin. */
1567 if(prIndex > 0)
1569 si->StdIn = *readEnd;
1570 *readEnd = 0;
1572 else if(cp->PipeFileSTDIN)
1574 /* Open a file for the child's stdin to read. */
1575 si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
1576 if(si->StdIn < 0)
1578 return 0;
1581 /* Set close-on-exec flag on the pipe's end. */
1582 if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
1584 return 0;
1587 else if(cp->PipeSharedSTDIN)
1589 si->StdIn = 0;
1591 else if(cp->PipeNativeSTDIN[0] >= 0)
1593 si->StdIn = cp->PipeNativeSTDIN[0];
1595 /* Set close-on-exec flag on the pipe's ends. The read end will
1596 be dup2-ed into the stdin descriptor after the fork but before
1597 the exec. */
1598 if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
1599 (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
1601 return 0;
1604 else
1606 si->StdIn = -1;
1609 /* Setup the process's stdout. */
1611 /* Create the pipe. */
1612 int p[2];
1613 if(pipe(p) < 0)
1615 return 0;
1617 *readEnd = p[0];
1618 si->StdOut = p[1];
1620 /* Set close-on-exec flag on the pipe's ends. */
1621 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
1622 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
1624 return 0;
1628 /* Replace the stdout pipe with a file if requested. In this case
1629 the select call will report that stdout is closed immediately. */
1630 if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
1632 if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
1634 return 0;
1638 /* Replace the stdout pipe with the parent's if requested. In this
1639 case the select call will report that stderr is closed
1640 immediately. */
1641 if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
1643 kwsysProcessCleanupDescriptor(&si->StdOut);
1644 si->StdOut = 1;
1647 /* Replace the stdout pipe with the native pipe provided if any. In
1648 this case the select call will report that stdout is closed
1649 immediately. */
1650 if(prIndex == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1] >= 0)
1652 if(!kwsysProcessSetupOutputPipeNative(&si->StdOut, cp->PipeNativeSTDOUT))
1654 return 0;
1658 /* Create the error reporting pipe. */
1659 if(pipe(si->ErrorPipe) < 0)
1661 return 0;
1664 /* Set close-on-exec flag on the error pipe's write end. */
1665 if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
1667 return 0;
1670 /* Fork off a child process. */
1671 cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
1672 if(cp->ForkPIDs[prIndex] < 0)
1674 return 0;
1677 if(cp->ForkPIDs[prIndex] == 0)
1679 /* Close the read end of the error reporting pipe. */
1680 close(si->ErrorPipe[0]);
1682 /* Setup the stdin, stdout, and stderr pipes. */
1683 if(si->StdIn > 0)
1685 dup2(si->StdIn, 0);
1687 else if(si->StdIn < 0)
1689 close(0);
1691 if(si->StdOut != 1)
1693 dup2(si->StdOut, 1);
1695 if(si->StdErr != 2)
1697 dup2(si->StdErr, 2);
1700 /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1701 All other pipe handles will be closed when exec succeeds. */
1702 fcntl(0, F_SETFD, 0);
1703 fcntl(1, F_SETFD, 0);
1704 fcntl(2, F_SETFD, 0);
1706 /* Restore all default signal handlers. */
1707 kwsysProcessRestoreDefaultSignalHandlers();
1709 /* Execute the real process. If successful, this does not return. */
1710 execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
1712 /* Failure. Report error to parent and terminate. */
1713 kwsysProcessChildErrorExit(si->ErrorPipe[1]);
1716 /* A child has been created. */
1717 ++cp->CommandsLeft;
1719 /* We are done with the error reporting pipe write end. */
1720 kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1722 /* Block until the child's exec call succeeds and closes the error
1723 pipe or writes data to the pipe to report an error. */
1725 kwsysProcess_ssize_t total = 0;
1726 kwsysProcess_ssize_t n = 1;
1727 /* Read the entire error message up to the length of our buffer. */
1728 while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
1730 /* Keep trying to read until the operation is not interrupted. */
1731 while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
1732 KWSYSPE_PIPE_BUFFER_SIZE-total)) < 0) &&
1733 (errno == EINTR));
1734 if(n > 0)
1736 total += n;
1740 /* We are done with the error reporting pipe read end. */
1741 kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1743 if(total > 0)
1745 /* The child failed to execute the process. */
1746 return 0;
1750 /* Successfully created this child process. */
1751 if(prIndex > 0 || si->StdIn > 0)
1753 /* The parent process does not need the input pipe read end. */
1754 kwsysProcessCleanupDescriptor(&si->StdIn);
1757 /* The parent process does not need the output pipe write ends. */
1758 if(si->StdOut != 1)
1760 kwsysProcessCleanupDescriptor(&si->StdOut);
1763 return 1;
1766 /*--------------------------------------------------------------------------*/
1767 static void kwsysProcessDestroy(kwsysProcess* cp)
1769 /* A child process has terminated. Reap it if it is one handled by
1770 this object. */
1771 int i;
1772 for(i=0; i < cp->NumberOfCommands; ++i)
1774 if(cp->ForkPIDs[i])
1776 int result;
1777 while(((result = waitpid(cp->ForkPIDs[i],
1778 &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
1779 (errno == EINTR));
1780 if(result > 0)
1782 /* This child has termianted. */
1783 cp->ForkPIDs[i] = 0;
1784 if(--cp->CommandsLeft == 0)
1786 /* All children have terminated. Close the signal pipe
1787 write end so that no more notifications are sent to this
1788 object. */
1789 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1791 /* TODO: Once the children have terminated, switch
1792 WaitForData to use a non-blocking read to get the
1793 rest of the data from the pipe. This is needed when
1794 grandchildren keep the output pipes open. */
1797 else if(result < 0 && cp->State != kwsysProcess_State_Error)
1799 /* Unexpected error. Report the first time this happens. */
1800 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1801 cp->State = kwsysProcess_State_Error;
1807 /*--------------------------------------------------------------------------*/
1808 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
1810 int fout;
1811 if(!name)
1813 return 1;
1816 /* Close the existing descriptor. */
1817 kwsysProcessCleanupDescriptor(p);
1819 /* Open a file for the pipe to write (permissions 644). */
1820 if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC,
1821 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
1823 return 0;
1826 /* Set close-on-exec flag on the pipe's end. */
1827 if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
1829 return 0;
1832 /* Assign the replacement descriptor. */
1833 *p = fout;
1834 return 1;
1837 /*--------------------------------------------------------------------------*/
1838 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
1840 /* Close the existing descriptor. */
1841 kwsysProcessCleanupDescriptor(p);
1843 /* Set close-on-exec flag on the pipe's ends. The proper end will
1844 be dup2-ed into the standard descriptor number after fork but
1845 before exec. */
1846 if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
1847 (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
1849 return 0;
1852 /* Assign the replacement descriptor. */
1853 *p = des[1];
1854 return 1;
1857 /*--------------------------------------------------------------------------*/
1858 /* Get the time at which either the process or user timeout will
1859 expire. Returns 1 if the user timeout is first, and 0 otherwise. */
1860 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
1861 kwsysProcessTime* timeoutTime)
1863 /* The first time this is called, we need to calculate the time at
1864 which the child will timeout. */
1865 if(cp->Timeout && cp->TimeoutTime.tv_sec < 0)
1867 kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
1868 cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
1871 /* Start with process timeout. */
1872 *timeoutTime = cp->TimeoutTime;
1874 /* Check if the user timeout is earlier. */
1875 if(userTimeout)
1877 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1878 kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
1879 kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
1880 userTimeoutLength);
1881 if(timeoutTime->tv_sec < 0 ||
1882 kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
1884 *timeoutTime = userTimeoutTime;
1885 return 1;
1888 return 0;
1891 /*--------------------------------------------------------------------------*/
1892 /* Get the length of time before the given timeout time arrives.
1893 Returns 1 if the time has already arrived, and 0 otherwise. */
1894 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
1895 double* userTimeout,
1896 kwsysProcessTimeNative* timeoutLength)
1898 if(timeoutTime->tv_sec < 0)
1900 /* No timeout time has been requested. */
1901 return 0;
1903 else
1905 /* Calculate the remaining time. */
1906 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1907 kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
1908 currentTime);
1909 if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
1911 /* Caller has explicitly requested a zero timeout. */
1912 timeLeft.tv_sec = 0;
1913 timeLeft.tv_usec = 0;
1916 if(timeLeft.tv_sec < 0)
1918 /* Timeout has already expired. */
1919 return 1;
1921 else
1923 /* There is some time left. */
1924 timeoutLength->tv_sec = timeLeft.tv_sec;
1925 timeoutLength->tv_usec = timeLeft.tv_usec;
1926 return 0;
1931 /*--------------------------------------------------------------------------*/
1932 static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
1934 kwsysProcessTime current;
1935 kwsysProcessTimeNative current_native;
1936 gettimeofday(&current_native, 0);
1937 current.tv_sec = (long)current_native.tv_sec;
1938 current.tv_usec = (long)current_native.tv_usec;
1939 return current;
1942 /*--------------------------------------------------------------------------*/
1943 static double kwsysProcessTimeToDouble(kwsysProcessTime t)
1945 return (double)t.tv_sec + t.tv_usec*0.000001;
1948 /*--------------------------------------------------------------------------*/
1949 static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
1951 kwsysProcessTime t;
1952 t.tv_sec = (long)d;
1953 t.tv_usec = (long)((d-t.tv_sec)*1000000);
1954 return t;
1957 /*--------------------------------------------------------------------------*/
1958 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
1960 return ((in1.tv_sec < in2.tv_sec) ||
1961 ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
1964 /*--------------------------------------------------------------------------*/
1965 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
1967 kwsysProcessTime out;
1968 out.tv_sec = in1.tv_sec + in2.tv_sec;
1969 out.tv_usec = in1.tv_usec + in2.tv_usec;
1970 if(out.tv_usec > 1000000)
1972 out.tv_usec -= 1000000;
1973 out.tv_sec += 1;
1975 return out;
1978 /*--------------------------------------------------------------------------*/
1979 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
1981 kwsysProcessTime out;
1982 out.tv_sec = in1.tv_sec - in2.tv_sec;
1983 out.tv_usec = in1.tv_usec - in2.tv_usec;
1984 if(out.tv_usec < 0)
1986 out.tv_usec += 1000000;
1987 out.tv_sec -= 1;
1989 return out;
1992 /*--------------------------------------------------------------------------*/
1993 #define KWSYSPE_CASE(type, str) \
1994 cp->ExitException = kwsysProcess_Exception_##type; \
1995 strcpy(cp->ExitExceptionString, str)
1996 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
1998 switch (sig)
2000 #ifdef SIGSEGV
2001 case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
2002 #endif
2003 #ifdef SIGBUS
2004 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2005 case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
2006 # endif
2007 #endif
2008 #ifdef SIGFPE
2009 case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
2010 #endif
2011 #ifdef SIGILL
2012 case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
2013 #endif
2014 #ifdef SIGINT
2015 case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
2016 #endif
2017 #ifdef SIGABRT
2018 case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
2019 #endif
2020 #ifdef SIGKILL
2021 case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
2022 #endif
2023 #ifdef SIGTERM
2024 case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
2025 #endif
2026 #ifdef SIGHUP
2027 case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
2028 #endif
2029 #ifdef SIGQUIT
2030 case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
2031 #endif
2032 #ifdef SIGTRAP
2033 case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
2034 #endif
2035 #ifdef SIGIOT
2036 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2037 case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
2038 # endif
2039 #endif
2040 #ifdef SIGUSR1
2041 case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
2042 #endif
2043 #ifdef SIGUSR2
2044 case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
2045 #endif
2046 #ifdef SIGPIPE
2047 case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
2048 #endif
2049 #ifdef SIGALRM
2050 case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
2051 #endif
2052 #ifdef SIGSTKFLT
2053 case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
2054 #endif
2055 #ifdef SIGCHLD
2056 case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
2057 #elif defined(SIGCLD)
2058 case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
2059 #endif
2060 #ifdef SIGCONT
2061 case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
2062 #endif
2063 #ifdef SIGSTOP
2064 case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
2065 #endif
2066 #ifdef SIGTSTP
2067 case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
2068 #endif
2069 #ifdef SIGTTIN
2070 case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
2071 #endif
2072 #ifdef SIGTTOU
2073 case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
2074 #endif
2075 #ifdef SIGURG
2076 case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
2077 #endif
2078 #ifdef SIGXCPU
2079 case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
2080 #endif
2081 #ifdef SIGXFSZ
2082 case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
2083 #endif
2084 #ifdef SIGVTALRM
2085 case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
2086 #endif
2087 #ifdef SIGPROF
2088 case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
2089 #endif
2090 #ifdef SIGWINCH
2091 case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
2092 #endif
2093 #ifdef SIGPOLL
2094 case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
2095 #endif
2096 #ifdef SIGIO
2097 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2098 case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
2099 # endif
2100 #endif
2101 #ifdef SIGPWR
2102 case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
2103 #endif
2104 #ifdef SIGSYS
2105 case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
2106 #endif
2107 #ifdef SIGUNUSED
2108 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2109 case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
2110 # endif
2111 #endif
2112 default:
2113 cp->ExitException = kwsysProcess_Exception_Other;
2114 sprintf(cp->ExitExceptionString, "Signal %d", sig);
2115 break;
2118 #undef KWSYSPE_CASE
2120 /*--------------------------------------------------------------------------*/
2121 /* When the child process encounters an error before its program is
2122 invoked, this is called to report the error to the parent and
2123 exit. */
2124 static void kwsysProcessChildErrorExit(int errorPipe)
2126 /* Construct the error message. */
2127 char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
2128 strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
2130 /* Report the error to the parent through the special pipe. */
2131 write(errorPipe, buffer, strlen(buffer));
2133 /* Terminate without cleanup. */
2134 _exit(1);
2137 /*--------------------------------------------------------------------------*/
2138 /* Restores all signal handlers to their default values. */
2139 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2141 struct sigaction act;
2142 memset(&act, 0, sizeof(struct sigaction));
2143 act.sa_handler = SIG_DFL;
2144 #ifdef SIGHUP
2145 sigaction(SIGHUP, &act, 0);
2146 #endif
2147 #ifdef SIGINT
2148 sigaction(SIGINT, &act, 0);
2149 #endif
2150 #ifdef SIGQUIT
2151 sigaction(SIGQUIT, &act, 0);
2152 #endif
2153 #ifdef SIGILL
2154 sigaction(SIGILL, &act, 0);
2155 #endif
2156 #ifdef SIGTRAP
2157 sigaction(SIGTRAP, &act, 0);
2158 #endif
2159 #ifdef SIGABRT
2160 sigaction(SIGABRT, &act, 0);
2161 #endif
2162 #ifdef SIGIOT
2163 sigaction(SIGIOT, &act, 0);
2164 #endif
2165 #ifdef SIGBUS
2166 sigaction(SIGBUS, &act, 0);
2167 #endif
2168 #ifdef SIGFPE
2169 sigaction(SIGFPE, &act, 0);
2170 #endif
2171 #ifdef SIGUSR1
2172 sigaction(SIGUSR1, &act, 0);
2173 #endif
2174 #ifdef SIGSEGV
2175 sigaction(SIGSEGV, &act, 0);
2176 #endif
2177 #ifdef SIGUSR2
2178 sigaction(SIGUSR2, &act, 0);
2179 #endif
2180 #ifdef SIGPIPE
2181 sigaction(SIGPIPE, &act, 0);
2182 #endif
2183 #ifdef SIGALRM
2184 sigaction(SIGALRM, &act, 0);
2185 #endif
2186 #ifdef SIGTERM
2187 sigaction(SIGTERM, &act, 0);
2188 #endif
2189 #ifdef SIGSTKFLT
2190 sigaction(SIGSTKFLT, &act, 0);
2191 #endif
2192 #ifdef SIGCLD
2193 sigaction(SIGCLD, &act, 0);
2194 #endif
2195 #ifdef SIGCHLD
2196 sigaction(SIGCHLD, &act, 0);
2197 #endif
2198 #ifdef SIGCONT
2199 sigaction(SIGCONT, &act, 0);
2200 #endif
2201 #ifdef SIGTSTP
2202 sigaction(SIGTSTP, &act, 0);
2203 #endif
2204 #ifdef SIGTTIN
2205 sigaction(SIGTTIN, &act, 0);
2206 #endif
2207 #ifdef SIGTTOU
2208 sigaction(SIGTTOU, &act, 0);
2209 #endif
2210 #ifdef SIGURG
2211 sigaction(SIGURG, &act, 0);
2212 #endif
2213 #ifdef SIGXCPU
2214 sigaction(SIGXCPU, &act, 0);
2215 #endif
2216 #ifdef SIGXFSZ
2217 sigaction(SIGXFSZ, &act, 0);
2218 #endif
2219 #ifdef SIGVTALRM
2220 sigaction(SIGVTALRM, &act, 0);
2221 #endif
2222 #ifdef SIGPROF
2223 sigaction(SIGPROF, &act, 0);
2224 #endif
2225 #ifdef SIGWINCH
2226 sigaction(SIGWINCH, &act, 0);
2227 #endif
2228 #ifdef SIGPOLL
2229 sigaction(SIGPOLL, &act, 0);
2230 #endif
2231 #ifdef SIGIO
2232 sigaction(SIGIO, &act, 0);
2233 #endif
2234 #ifdef SIGPWR
2235 sigaction(SIGPWR, &act, 0);
2236 #endif
2237 #ifdef SIGSYS
2238 sigaction(SIGSYS, &act, 0);
2239 #endif
2240 #ifdef SIGUNUSED
2241 sigaction(SIGUNUSED, &act, 0);
2242 #endif
2245 /*--------------------------------------------------------------------------*/
2246 static void kwsysProcessExit(void)
2248 _exit(0);
2251 /*--------------------------------------------------------------------------*/
2252 static pid_t kwsysProcessFork(kwsysProcess* cp,
2253 kwsysProcessCreateInformation* si)
2255 /* Create a detached process if requested. */
2256 if(cp->OptionDetach)
2258 /* Create an intermediate process. */
2259 pid_t middle_pid = fork();
2260 if(middle_pid < 0)
2262 /* Fork failed. Return as if we were not detaching. */
2263 return middle_pid;
2265 else if(middle_pid == 0)
2267 /* This is the intermediate process. Create the real child. */
2268 pid_t child_pid = fork();
2269 if(child_pid == 0)
2271 /* This is the real child process. There is nothing to do here. */
2272 return 0;
2274 else
2276 /* Use the error pipe to report the pid to the real parent. */
2277 while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
2278 (errno == EINTR));
2280 /* Exit without cleanup. The parent holds all resources. */
2281 kwsysProcessExit();
2282 return 0; /* Never reached, but avoids SunCC warning. */
2285 else
2287 /* This is the original parent process. The intermediate
2288 process will use the error pipe to report the pid of the
2289 detached child. */
2290 pid_t child_pid;
2291 int status;
2292 while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
2293 (errno == EINTR));
2295 /* Wait for the intermediate process to exit and clean it up. */
2296 while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
2297 return child_pid;
2300 else
2302 /* Not creating a detached process. Use normal fork. */
2303 return fork();
2307 /*--------------------------------------------------------------------------*/
2308 /* We try to obtain process information by invoking the ps command.
2309 Here we define the command to call on each platform and the
2310 corresponding parsing format string. The parsing format should
2311 have two integers to store: the pid and then the ppid. */
2312 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
2313 # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2314 # define KWSYSPE_PS_FORMAT "%d %d\n"
2315 #elif defined(__hpux) || defined(__sparc) || defined(__sgi) || defined(_AIX)
2316 # define KWSYSPE_PS_COMMAND "ps -ef"
2317 # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
2318 #elif defined(__CYGWIN__)
2319 # define KWSYSPE_PS_COMMAND "ps aux"
2320 # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
2321 #endif
2323 /*--------------------------------------------------------------------------*/
2324 static void kwsysProcessKill(pid_t process_id)
2326 #if defined(__linux__) || defined(__CYGWIN__)
2327 DIR* procdir;
2328 #endif
2330 /* Kill the process now to make sure it does not create more
2331 children. Do not reap it yet so we can identify its existing
2332 children. There is a small race condition here. If the child
2333 forks after we begin looking for children below but before it
2334 receives this kill signal we might miss a child. Also we might
2335 not be able to catch up to a fork bomb. */
2336 kill(process_id, SIGKILL);
2338 /* Kill all children if we can find them. */
2339 #if defined(__linux__) || defined(__CYGWIN__)
2340 /* First try using the /proc filesystem. */
2341 if((procdir = opendir("/proc")) != NULL)
2343 #if defined(MAXPATHLEN)
2344 char fname[MAXPATHLEN];
2345 #elif defined(PATH_MAX)
2346 char fname[PATH_MAX];
2347 #else
2348 char fname[4096];
2349 #endif
2350 char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
2351 struct dirent* d;
2353 /* Each process has a directory in /proc whose name is the pid.
2354 Within this directory is a file called stat that has the
2355 following format:
2357 pid (command line) status ppid ...
2359 We want to get the ppid for all processes. Those that have
2360 process_id as their parent should be recursively killed. */
2361 for(d = readdir(procdir); d; d = readdir(procdir))
2363 int pid;
2364 if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
2366 struct stat finfo;
2367 sprintf(fname, "/proc/%d/stat", pid);
2368 if(stat(fname, &finfo) == 0)
2370 FILE* f = fopen(fname, "r");
2371 if(f)
2373 int nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
2374 buffer[nread] = '\0';
2375 if(nread > 0)
2377 const char* rparen = strrchr(buffer, ')');
2378 int ppid;
2379 if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
2381 if(ppid == process_id)
2383 /* Recursively kill this child and its children. */
2384 kwsysProcessKill(pid);
2388 fclose(f);
2393 closedir(procdir);
2395 else
2396 #endif
2398 #if defined(KWSYSPE_PS_COMMAND)
2399 /* Try running "ps" to get the process information. */
2400 FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
2402 /* Make sure the process started and provided a valid header. */
2403 if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
2405 /* Look for processes whose parent is the process being killed. */
2406 int pid, ppid;
2407 while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
2409 if(ppid == process_id)
2411 /* Recursively kill this child and its children. */
2412 kwsysProcessKill(pid);
2417 /* We are done with the ps process. */
2418 if(ps)
2420 pclose(ps);
2422 #endif
2426 /*--------------------------------------------------------------------------*/
2427 /* Global set of executing processes for use by the signal handler.
2428 This global instance will be zero-initialized by the compiler. */
2429 typedef struct kwsysProcessInstances_s
2431 int Count;
2432 int Size;
2433 kwsysProcess** Processes;
2434 } kwsysProcessInstances;
2435 static kwsysProcessInstances kwsysProcesses;
2437 /* The old SIGCHLD handler. */
2438 static struct sigaction kwsysProcessesOldSigChldAction;
2440 /*--------------------------------------------------------------------------*/
2441 static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
2443 /* Block SIGCHLD while we update the set of pipes to check.
2444 TODO: sigprocmask is undefined for threaded apps. See
2445 pthread_sigmask. */
2446 sigset_t newset;
2447 sigset_t oldset;
2448 sigemptyset(&newset);
2449 sigaddset(&newset, SIGCHLD);
2450 sigprocmask(SIG_BLOCK, &newset, &oldset);
2452 /* Store the new set in that seen by the signal handler. */
2453 kwsysProcesses = *newProcesses;
2455 /* Restore the signal mask to the previous setting. */
2456 sigprocmask(SIG_SETMASK, &oldset, 0);
2459 /*--------------------------------------------------------------------------*/
2460 static int kwsysProcessesAdd(kwsysProcess* cp)
2462 /* Create a pipe through which the signal handler can notify the
2463 given process object that a child has exited. */
2465 /* Create the pipe. */
2466 int p[2];
2467 if(pipe(p) < 0)
2469 return 0;
2472 /* Store the pipes now to be sure they are cleaned up later. */
2473 cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
2474 cp->SignalPipe = p[1];
2476 /* Switch the pipe to non-blocking mode so that reading a byte can
2477 be an atomic test-and-set. */
2478 if(!kwsysProcessSetNonBlocking(p[0]) ||
2479 !kwsysProcessSetNonBlocking(p[1]))
2481 return 0;
2484 /* The children do not need this pipe. Set close-on-exec flag on
2485 the pipe's ends. */
2486 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
2487 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
2489 return 0;
2493 /* Attempt to add the given signal pipe to the signal handler set. */
2496 /* Make sure there is enough space for the new signal pipe. */
2497 kwsysProcessInstances oldProcesses = kwsysProcesses;
2498 kwsysProcessInstances newProcesses = oldProcesses;
2499 if(oldProcesses.Count == oldProcesses.Size)
2501 /* Start with enough space for a small number of process instances
2502 and double the size each time more is needed. */
2503 newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
2505 /* Try allocating the new block of memory. */
2506 if((newProcesses.Processes = ((kwsysProcess**)
2507 malloc(newProcesses.Size*
2508 sizeof(kwsysProcess*)))))
2510 /* Copy the old pipe set to the new memory. */
2511 if(oldProcesses.Count > 0)
2513 memcpy(newProcesses.Processes, oldProcesses.Processes,
2514 (oldProcesses.Count * sizeof(kwsysProcess*)));
2517 else
2519 /* Failed to allocate memory for the new signal pipe set. */
2520 return 0;
2524 /* Append the new signal pipe to the set. */
2525 newProcesses.Processes[newProcesses.Count++] = cp;
2527 /* Store the new set in that seen by the signal handler. */
2528 kwsysProcessesUpdate(&newProcesses);
2530 /* Free the original pipes if new ones were allocated. */
2531 if(newProcesses.Processes != oldProcesses.Processes)
2533 free(oldProcesses.Processes);
2536 /* If this is the first process, enable the signal handler. */
2537 if(newProcesses.Count == 1)
2539 /* Install our handler for SIGCHLD. Repeat call until it is not
2540 interrupted. */
2541 struct sigaction newSigChldAction;
2542 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2543 #if KWSYSPE_USE_SIGINFO
2544 newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
2545 newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2546 # ifdef SA_RESTART
2547 newSigChldAction.sa_flags |= SA_RESTART;
2548 # endif
2549 #else
2550 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2551 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2552 #endif
2553 while((sigaction(SIGCHLD, &newSigChldAction,
2554 &kwsysProcessesOldSigChldAction) < 0) &&
2555 (errno == EINTR));
2559 return 1;
2562 /*--------------------------------------------------------------------------*/
2563 static void kwsysProcessesRemove(kwsysProcess* cp)
2565 /* Attempt to remove the given signal pipe from the signal handler set. */
2567 /* Find the given process in the set. */
2568 kwsysProcessInstances newProcesses = kwsysProcesses;
2569 int i;
2570 for(i=0; i < newProcesses.Count; ++i)
2572 if(newProcesses.Processes[i] == cp)
2574 break;
2577 if(i < newProcesses.Count)
2579 /* Remove the process from the set. */
2580 --newProcesses.Count;
2581 for(; i < newProcesses.Count; ++i)
2583 newProcesses.Processes[i] = newProcesses.Processes[i+1];
2586 /* If this was the last process, disable the signal handler. */
2587 if(newProcesses.Count == 0)
2589 /* Restore the SIGCHLD handler. Repeat call until it is not
2590 interrupted. */
2591 while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
2592 (errno == EINTR));
2594 /* Free the table of process pointers since it is now empty.
2595 This is safe because the signal handler has been removed. */
2596 newProcesses.Size = 0;
2597 free(newProcesses.Processes);
2598 newProcesses.Processes = 0;
2601 /* Store the new set in that seen by the signal handler. */
2602 kwsysProcessesUpdate(&newProcesses);
2606 /* Close the pipe through which the signal handler may have notified
2607 the given process object that a child has exited. */
2608 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
2611 /*--------------------------------------------------------------------------*/
2612 static void kwsysProcessesSignalHandler(int signum
2613 #if KWSYSPE_USE_SIGINFO
2614 , siginfo_t* info, void* ucontext
2615 #endif
2618 (void)signum;
2619 #if KWSYSPE_USE_SIGINFO
2620 (void)info;
2621 (void)ucontext;
2622 #endif
2624 /* Signal all process objects that a child has terminated. */
2626 int i;
2627 for(i=0; i < kwsysProcesses.Count; ++i)
2629 /* Set the pipe in a signalled state. */
2630 char buf = 1;
2631 kwsysProcess* cp = kwsysProcesses.Processes[i];
2632 read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
2633 write(cp->SignalPipe, &buf, 1);
2637 #if !KWSYSPE_USE_SIGINFO
2638 /* Re-Install our handler for SIGCHLD. Repeat call until it is not
2639 interrupted. */
2641 struct sigaction newSigChldAction;
2642 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2643 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2644 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2645 while((sigaction(SIGCHLD, &newSigChldAction,
2646 &kwsysProcessesOldSigChldAction) < 0) &&
2647 (errno == EINTR));
2649 #endif
2652 /*--------------------------------------------------------------------------*/
2653 static int kwsysProcessAppendByte(char* local,
2654 char** begin, char** end,
2655 int* size, char c)
2657 /* Allocate space for the character. */
2658 if((*end - *begin) >= *size)
2660 kwsysProcess_ptrdiff_t length = *end - *begin;
2661 char* newBuffer = (char*)malloc(*size*2);
2662 if(!newBuffer)
2664 return 0;
2666 memcpy(newBuffer, *begin, length*sizeof(char));
2667 if(*begin != local)
2669 free(*begin);
2671 *begin = newBuffer;
2672 *end = *begin + length;
2673 *size *= 2;
2676 /* Store the character. */
2677 *(*end)++ = c;
2678 return 1;
2681 /*--------------------------------------------------------------------------*/
2682 static int kwsysProcessAppendArgument(char** local,
2683 char*** begin, char*** end,
2684 int* size,
2685 char* arg_local,
2686 char** arg_begin, char** arg_end,
2687 int* arg_size)
2689 /* Append a null-terminator to the argument string. */
2690 if(!kwsysProcessAppendByte(arg_local, arg_begin, arg_end, arg_size, '\0'))
2692 return 0;
2695 /* Allocate space for the argument pointer. */
2696 if((*end - *begin) >= *size)
2698 kwsysProcess_ptrdiff_t length = *end - *begin;
2699 char** newPointers = (char**)malloc(*size*2*sizeof(char*));
2700 if(!newPointers)
2702 return 0;
2704 memcpy(newPointers, *begin, length*sizeof(char*));
2705 if(*begin != local)
2707 free(*begin);
2709 *begin = newPointers;
2710 *end = *begin + length;
2711 *size *= 2;
2714 /* Allocate space for the argument string. */
2715 **end = (char*)malloc(*arg_end - *arg_begin);
2716 if(!**end)
2718 return 0;
2721 /* Store the argument in the command array. */
2722 memcpy(**end, *arg_begin, *arg_end - *arg_begin);
2723 ++(*end);
2725 /* Reset the argument to be empty. */
2726 *arg_end = *arg_begin;
2728 return 1;
2731 /*--------------------------------------------------------------------------*/
2732 #define KWSYSPE_LOCAL_BYTE_COUNT 1024
2733 #define KWSYSPE_LOCAL_ARGS_COUNT 32
2734 static char** kwsysProcessParseVerbatimCommand(const char* command)
2736 /* Create a buffer for argument pointers during parsing. */
2737 char* local_pointers[KWSYSPE_LOCAL_ARGS_COUNT];
2738 int pointers_size = KWSYSPE_LOCAL_ARGS_COUNT;
2739 char** pointer_begin = local_pointers;
2740 char** pointer_end = pointer_begin;
2742 /* Create a buffer for argument strings during parsing. */
2743 char local_buffer[KWSYSPE_LOCAL_BYTE_COUNT];
2744 int buffer_size = KWSYSPE_LOCAL_BYTE_COUNT;
2745 char* buffer_begin = local_buffer;
2746 char* buffer_end = buffer_begin;
2748 /* Parse the command string. Try to behave like a UNIX shell. */
2749 char** newCommand = 0;
2750 const char* c = command;
2751 int in_argument = 0;
2752 int in_escape = 0;
2753 int in_single = 0;
2754 int in_double = 0;
2755 int failed = 0;
2756 for(;*c; ++c)
2758 if(in_escape)
2760 /* This character is escaped so do no special handling. */
2761 if(!in_argument)
2763 in_argument = 1;
2765 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2766 &buffer_end, &buffer_size, *c))
2768 failed = 1;
2769 break;
2771 in_escape = 0;
2773 else if(*c == '\\' && !in_single)
2775 /* The next character should be escaped. */
2776 in_escape = 1;
2778 else if(*c == '\'' && !in_double)
2780 /* Enter or exit single-quote state. */
2781 if(in_single)
2783 in_single = 0;
2785 else
2787 in_single = 1;
2788 if(!in_argument)
2790 in_argument = 1;
2794 else if(*c == '"' && !in_single)
2796 /* Enter or exit double-quote state. */
2797 if(in_double)
2799 in_double = 0;
2801 else
2803 in_double = 1;
2804 if(!in_argument)
2806 in_argument = 1;
2810 else if(isspace(*c))
2812 if(in_argument)
2814 if(in_single || in_double)
2816 /* This space belongs to a quoted argument. */
2817 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2818 &buffer_end, &buffer_size, *c))
2820 failed = 1;
2821 break;
2824 else
2826 /* This argument has been terminated by whitespace. */
2827 if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
2828 &pointer_end, &pointers_size,
2829 local_buffer, &buffer_begin,
2830 &buffer_end, &buffer_size))
2832 failed = 1;
2833 break;
2835 in_argument = 0;
2839 else
2841 /* This character belong to an argument. */
2842 if(!in_argument)
2844 in_argument = 1;
2846 if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
2847 &buffer_end, &buffer_size, *c))
2849 failed = 1;
2850 break;
2855 /* Finish the last argument. */
2856 if(in_argument)
2858 if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
2859 &pointer_end, &pointers_size,
2860 local_buffer, &buffer_begin,
2861 &buffer_end, &buffer_size))
2863 failed = 1;
2867 /* If we still have memory allocate space for the new command
2868 buffer. */
2869 if(!failed)
2871 kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin;
2872 newCommand = (char**)malloc((n+1)*sizeof(char*));
2875 if(newCommand)
2877 /* Copy the arguments into the new command buffer. */
2878 kwsysProcess_ptrdiff_t n = pointer_end - pointer_begin;
2879 memcpy(newCommand, pointer_begin, sizeof(char*)*n);
2880 newCommand[n] = 0;
2882 else
2884 /* Free arguments already allocated. */
2885 while(pointer_end != pointer_begin)
2887 free(*(--pointer_end));
2891 /* Free temporary buffers. */
2892 if(pointer_begin != local_pointers)
2894 free(pointer_begin);
2896 if(buffer_begin != local_buffer)
2898 free(buffer_begin);
2901 /* Return the final command buffer. */
2902 return newCommand;