1 /*============================================================================
2 KWSys - Kitware System Library
3 Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
5 Distributed under the OSI-approved BSD License (the "License");
6 see accompanying file Copyright.txt for details.
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License for more information.
11 ============================================================================*/
12 #include "kwsysPrivate.h"
13 #include KWSYS_HEADER(Process.h)
14 #include KWSYS_HEADER(System.h)
16 /* Work-around CMake dependency scanning limitation. This must
17 duplicate the above list of headers. */
19 # include "Process.h.in"
20 # include "System.h.in"
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
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
50 #if defined(__CYGWIN__)
51 /* Increase the file descriptor limit for select() before including
52 related system headers. (Default: 64) */
53 # define FD_SETSIZE 16384
56 #include <stddef.h> /* ptrdiff_t */
57 #include <stdio.h> /* snprintf */
58 #include <stdlib.h> /* malloc, free */
59 #include <string.h> /* strdup, strerror, memset */
60 #include <sys/time.h> /* struct timeval */
61 #include <sys/types.h> /* pid_t, fd_set */
62 #include <sys/wait.h> /* waitpid */
63 #include <sys/stat.h> /* open mode */
64 #include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
65 #include <fcntl.h> /* fcntl */
66 #include <errno.h> /* errno */
67 #include <time.h> /* gettimeofday */
68 #include <signal.h> /* sigaction */
69 #include <dirent.h> /* DIR, dirent */
70 #include <ctype.h> /* isspace */
73 # define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
75 # define KWSYSPE_VMS_NONBLOCK
78 #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
79 typedef ptrdiff_t kwsysProcess_ptrdiff_t;
81 typedef int kwsysProcess_ptrdiff_t;
84 #if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
85 typedef ssize_t kwsysProcess_ssize_t;
87 typedef int kwsysProcess_ssize_t;
90 #if defined(__BEOS__) && !defined(__ZETA__)
91 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
92 # include <be/kernel/OS.h>
93 static inline void kwsysProcess_usleep(unsigned int msec)
98 # define kwsysProcess_usleep usleep
102 * BeOS's select() works like WinSock: it's for networking only, and
103 * doesn't work with Unix file handles...socket and file handles are
104 * different namespaces (the same descriptor means different things in
107 * So on Unix-like systems where select() is flakey, we'll set the
108 * pipes' file handles to be non-blocking and just poll them directly
111 #if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__)
112 # define KWSYSPE_USE_SELECT 1
115 /* Some platforms do not have siginfo on their signal handlers. */
116 #if defined(SA_SIGINFO) && !defined(__BEOS__)
117 # define KWSYSPE_USE_SIGINFO 1
120 /* The number of pipes for the child's output. The standard stdout
121 and stderr pipes are the first two. One more pipe is used to
122 detect when the child process has terminated. The third pipe is
123 not given to the child process, so it cannot close it until it
125 #define KWSYSPE_PIPE_COUNT 3
126 #define KWSYSPE_PIPE_STDOUT 0
127 #define KWSYSPE_PIPE_STDERR 1
128 #define KWSYSPE_PIPE_SIGNAL 2
130 /* The maximum amount to read from a pipe at a time. */
131 #define KWSYSPE_PIPE_BUFFER_SIZE 1024
133 /* Keep track of times using a signed representation. Switch to the
134 native (possibly unsigned) representation only when calling native
136 typedef struct timeval kwsysProcessTimeNative;
137 typedef struct kwsysProcessTime_s kwsysProcessTime;
138 struct kwsysProcessTime_s
144 typedef struct kwsysProcessCreateInformation_s
150 } kwsysProcessCreateInformation;
152 /*--------------------------------------------------------------------------*/
153 static int kwsysProcessInitialize(kwsysProcess* cp);
154 static void kwsysProcessCleanup(kwsysProcess* cp, int error);
155 static void kwsysProcessCleanupDescriptor(int* pfd);
156 static void kwsysProcessClosePipes(kwsysProcess* cp);
157 static int kwsysProcessSetNonBlocking(int fd);
158 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
159 kwsysProcessCreateInformation* si, int* readEnd);
160 static void kwsysProcessDestroy(kwsysProcess* cp);
161 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
162 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]);
163 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
164 kwsysProcessTime* timeoutTime);
165 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
167 kwsysProcessTimeNative* timeoutLength,
169 static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
170 static double kwsysProcessTimeToDouble(kwsysProcessTime t);
171 static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
172 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
173 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
174 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
175 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
176 static void kwsysProcessChildErrorExit(int errorPipe);
177 static void kwsysProcessRestoreDefaultSignalHandlers(void);
178 static pid_t kwsysProcessFork(kwsysProcess* cp,
179 kwsysProcessCreateInformation* si);
180 static void kwsysProcessKill(pid_t process_id);
182 static int kwsysProcessSetVMSFeature(const char* name, int value);
184 static int kwsysProcessesAdd(kwsysProcess* cp);
185 static void kwsysProcessesRemove(kwsysProcess* cp);
186 #if KWSYSPE_USE_SIGINFO
187 static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
190 static void kwsysProcessesSignalHandler(int signum);
193 /*--------------------------------------------------------------------------*/
194 /* Structure containing data used to implement the child's execution. */
195 struct kwsysProcess_s
197 /* The command lines to execute. */
199 int NumberOfCommands;
201 /* Descriptors for the read ends of the child's output pipes and
203 int PipeReadEnds[KWSYSPE_PIPE_COUNT];
205 /* Write descriptor for child termination signal pipe. */
208 /* Buffer for pipe data. */
209 char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
211 /* Process IDs returned by the calls to fork. */
214 /* Flag for whether the children were terminated by a faild select. */
217 /* The timeout length. */
220 /* The working directory for the process. */
221 char* WorkingDirectory;
223 /* Whether to create the child as a detached process. */
226 /* Whether the child was created as a detached process. */
229 /* Whether to treat command lines as verbatim. */
232 /* Time at which the child started. Negative for no timeout. */
233 kwsysProcessTime StartTime;
235 /* Time at which the child will timeout. Negative for no timeout. */
236 kwsysProcessTime TimeoutTime;
238 /* Flag for whether the timeout expired. */
241 /* The number of pipes left open during execution. */
244 #if KWSYSPE_USE_SELECT
245 /* File descriptor set for call to select. */
249 /* The number of children still executing. */
252 /* The current status of the child process. */
255 /* The exceptional behavior that terminated the child process, if
259 /* The exit code of the child process. */
262 /* The exit value of the child process, if any. */
265 /* Whether the process was killed. */
268 /* Buffer for error message in case of failure. */
269 char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
271 /* Description for the ExitException. */
272 char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
274 /* The exit codes of each child process in the pipeline. */
275 int* CommandExitCodes;
277 /* Name of files to which stdin and stdout pipes are attached. */
279 char* PipeFileSTDOUT;
280 char* PipeFileSTDERR;
282 /* Whether each pipe is shared with the parent process. */
284 int PipeSharedSTDOUT;
285 int PipeSharedSTDERR;
287 /* Native pipes provided by the user. */
288 int PipeNativeSTDIN[2];
289 int PipeNativeSTDOUT[2];
290 int PipeNativeSTDERR[2];
292 /* The real working directory of this process. */
293 int RealWorkingDirectoryLength;
294 char* RealWorkingDirectory;
297 /*--------------------------------------------------------------------------*/
298 kwsysProcess* kwsysProcess_New(void)
300 /* Allocate a process control structure. */
301 kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
306 memset(cp, 0, sizeof(kwsysProcess));
308 /* Share stdin with the parent process by default. */
309 cp->PipeSharedSTDIN = 1;
311 /* No native pipes by default. */
312 cp->PipeNativeSTDIN[0] = -1;
313 cp->PipeNativeSTDIN[1] = -1;
314 cp->PipeNativeSTDOUT[0] = -1;
315 cp->PipeNativeSTDOUT[1] = -1;
316 cp->PipeNativeSTDERR[0] = -1;
317 cp->PipeNativeSTDERR[1] = -1;
319 /* Set initial status. */
320 cp->State = kwsysProcess_State_Starting;
325 /*--------------------------------------------------------------------------*/
326 void kwsysProcess_Delete(kwsysProcess* cp)
328 /* Make sure we have an instance. */
334 /* If the process is executing, wait for it to finish. */
335 if(cp->State == kwsysProcess_State_Executing)
339 kwsysProcess_Disown(cp);
343 kwsysProcess_WaitForExit(cp, 0);
348 kwsysProcess_SetCommand(cp, 0);
349 kwsysProcess_SetWorkingDirectory(cp, 0);
350 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
351 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
352 kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
353 if(cp->CommandExitCodes)
355 free(cp->CommandExitCodes);
360 /*--------------------------------------------------------------------------*/
361 int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
368 for(i=0; i < cp->NumberOfCommands; ++i)
370 char** c = cp->Commands[i];
375 free(cp->Commands[i]);
377 cp->NumberOfCommands = 0;
385 return kwsysProcess_AddCommand(cp, command);
390 /*--------------------------------------------------------------------------*/
391 int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
393 int newNumberOfCommands;
396 /* Make sure we have a command to add. */
397 if(!cp || !command || !*command)
402 /* Allocate a new array for command pointers. */
403 newNumberOfCommands = cp->NumberOfCommands + 1;
405 (char***)malloc(sizeof(char**) *(size_t)(newNumberOfCommands))))
411 /* Copy any existing commands into the new array. */
414 for(i=0; i < cp->NumberOfCommands; ++i)
416 newCommands[i] = cp->Commands[i];
420 /* Add the new command. */
423 /* In order to run the given command line verbatim we need to
425 newCommands[cp->NumberOfCommands] =
426 kwsysSystem_Parse_CommandForUnix(*command, 0);
427 if(!newCommands[cp->NumberOfCommands] ||
428 !newCommands[cp->NumberOfCommands][0])
430 /* Out of memory or no command parsed. */
437 /* Copy each argument string individually. */
438 char const* const* c = command;
439 kwsysProcess_ptrdiff_t n = 0;
440 kwsysProcess_ptrdiff_t i = 0;
443 newCommands[cp->NumberOfCommands] =
444 (char**)malloc((size_t)(n+1)*sizeof(char*));
445 if(!newCommands[cp->NumberOfCommands])
453 newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
454 if(!newCommands[cp->NumberOfCommands][i])
464 free(newCommands[cp->NumberOfCommands][i-1]);
469 newCommands[cp->NumberOfCommands][n] = 0;
472 /* Successfully allocated new command array. Free the old array. */
474 cp->Commands = newCommands;
475 cp->NumberOfCommands = newNumberOfCommands;
480 /*--------------------------------------------------------------------------*/
481 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
487 cp->Timeout = timeout;
494 /*--------------------------------------------------------------------------*/
495 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
501 if(cp->WorkingDirectory == dir)
505 if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
509 if(cp->WorkingDirectory)
511 free(cp->WorkingDirectory);
512 cp->WorkingDirectory = 0;
516 cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
517 if(!cp->WorkingDirectory)
521 strcpy(cp->WorkingDirectory, dir);
526 /*--------------------------------------------------------------------------*/
527 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
536 case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
537 case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
538 case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
548 *pfile = malloc(strlen(file)+1);
553 strcpy(*pfile, file);
556 /* If we are redirecting the pipe, do not share it or use a native
560 kwsysProcess_SetPipeNative(cp, prPipe, 0);
561 kwsysProcess_SetPipeShared(cp, prPipe, 0);
566 /*--------------------------------------------------------------------------*/
567 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
576 case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
577 case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
578 case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
582 /* If we are sharing the pipe, do not redirect it to a file or use a
586 kwsysProcess_SetPipeFile(cp, prPipe, 0);
587 kwsysProcess_SetPipeNative(cp, prPipe, 0);
591 /*--------------------------------------------------------------------------*/
592 void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
594 int* pPipeNative = 0;
603 case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
604 case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
605 case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
609 /* Copy the native pipe descriptors provided. */
612 pPipeNative[0] = p[0];
613 pPipeNative[1] = p[1];
621 /* If we are using a native pipe, do not share it or redirect it to
625 kwsysProcess_SetPipeFile(cp, prPipe, 0);
626 kwsysProcess_SetPipeShared(cp, prPipe, 0);
630 /*--------------------------------------------------------------------------*/
631 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
640 case kwsysProcess_Option_Detach: return cp->OptionDetach;
641 case kwsysProcess_Option_Verbatim: return cp->Verbatim;
646 /*--------------------------------------------------------------------------*/
647 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
656 case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
657 case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
662 /*--------------------------------------------------------------------------*/
663 int kwsysProcess_GetState(kwsysProcess* cp)
665 return cp? cp->State : kwsysProcess_State_Error;
668 /*--------------------------------------------------------------------------*/
669 int kwsysProcess_GetExitException(kwsysProcess* cp)
671 return cp? cp->ExitException : kwsysProcess_Exception_Other;
674 /*--------------------------------------------------------------------------*/
675 int kwsysProcess_GetExitCode(kwsysProcess* cp)
677 return cp? cp->ExitCode : 0;
680 /*--------------------------------------------------------------------------*/
681 int kwsysProcess_GetExitValue(kwsysProcess* cp)
683 return cp? cp->ExitValue : -1;
686 /*--------------------------------------------------------------------------*/
687 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
691 return "Process management structure could not be allocated";
693 else if(cp->State == kwsysProcess_State_Error)
695 return cp->ErrorMessage;
700 /*--------------------------------------------------------------------------*/
701 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
705 return "GetExceptionString called with NULL process management structure";
707 else if(cp->State == kwsysProcess_State_Exception)
709 return cp->ExitExceptionString;
711 return "No exception";
714 /*--------------------------------------------------------------------------*/
715 void kwsysProcess_Execute(kwsysProcess* cp)
718 kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
720 /* Do not execute a second copy simultaneously. */
721 if(!cp || cp->State == kwsysProcess_State_Executing)
726 /* Make sure we have something to run. */
727 if(cp->NumberOfCommands < 1)
729 strcpy(cp->ErrorMessage, "No command");
730 cp->State = kwsysProcess_State_Error;
734 /* Initialize the control structure for a new process. */
735 if(!kwsysProcessInitialize(cp))
737 strcpy(cp->ErrorMessage, "Out of memory");
738 cp->State = kwsysProcess_State_Error;
743 /* Make sure pipes behave like streams on VMS. */
744 if(!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1))
746 kwsysProcessCleanup(cp, 1);
751 /* Save the real working directory of this process and change to
752 the working directory for the child processes. This is needed
753 to make pipe file paths evaluate correctly. */
754 if(cp->WorkingDirectory)
757 if(!getcwd(cp->RealWorkingDirectory,
758 (size_t)(cp->RealWorkingDirectoryLength)))
760 kwsysProcessCleanup(cp, 1);
764 /* Some platforms specify that the chdir call may be
765 interrupted. Repeat the call until it finishes. */
766 while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
769 kwsysProcessCleanup(cp, 1);
774 /* If not running a detached child, add this object to the global
775 set of process objects that wish to be notified when a child
777 if(!cp->OptionDetach)
779 if(!kwsysProcessesAdd(cp))
781 kwsysProcessCleanup(cp, 1);
786 /* Setup the stderr pipe to be shared by all processes. */
788 /* Create the pipe. */
790 if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
792 kwsysProcessCleanup(cp, 1);
796 /* Store the pipe. */
797 cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
800 /* Set close-on-exec flag on the pipe's ends. */
801 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
802 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
804 kwsysProcessCleanup(cp, 1);
805 kwsysProcessCleanupDescriptor(&si.StdErr);
809 /* Set to non-blocking in case select lies, or for the polling
811 if(!kwsysProcessSetNonBlocking(p[0]))
813 kwsysProcessCleanup(cp, 1);
814 kwsysProcessCleanupDescriptor(&si.StdErr);
819 /* Replace the stderr pipe with a file if requested. In this case
820 the select call will report that stderr is closed immediately. */
821 if(cp->PipeFileSTDERR)
823 if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
825 kwsysProcessCleanup(cp, 1);
826 kwsysProcessCleanupDescriptor(&si.StdErr);
831 /* Replace the stderr pipe with the parent's if requested. In this
832 case the select call will report that stderr is closed
834 if(cp->PipeSharedSTDERR)
836 kwsysProcessCleanupDescriptor(&si.StdErr);
840 /* Replace the stderr pipe with the native pipe provided if any. In
841 this case the select call will report that stderr is closed
843 if(cp->PipeNativeSTDERR[1] >= 0)
845 if(!kwsysProcessSetupOutputPipeNative(&si.StdErr, cp->PipeNativeSTDERR))
847 kwsysProcessCleanup(cp, 1);
848 kwsysProcessCleanupDescriptor(&si.StdErr);
853 /* The timeout period starts now. */
854 cp->StartTime = kwsysProcessTimeGetCurrent();
855 cp->TimeoutTime.tv_sec = -1;
856 cp->TimeoutTime.tv_usec = -1;
858 /* Create the pipeline of processes. */
862 for(i=0; i < cp->NumberOfCommands; ++i)
864 if(!kwsysProcessCreate(cp, i, &si, &readEnd))
869 /* Set the output pipe of the last process to be non-blocking in
870 case select lies, or for the polling implementation. */
871 if(i == (cp->NumberOfCommands-1) && !kwsysProcessSetNonBlocking(readEnd))
878 kwsysProcessCleanup(cp, 1);
880 /* Release resources that may have been allocated for this
881 process before an error occurred. */
882 kwsysProcessCleanupDescriptor(&readEnd);
885 kwsysProcessCleanupDescriptor(&si.StdIn);
889 kwsysProcessCleanupDescriptor(&si.StdOut);
893 kwsysProcessCleanupDescriptor(&si.StdErr);
895 kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
896 kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
900 /* Save a handle to the output pipe for the last process. */
901 cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
904 /* The parent process does not need the output pipe write ends. */
907 kwsysProcessCleanupDescriptor(&si.StdErr);
910 /* Restore the working directory. */
911 if(cp->RealWorkingDirectory)
913 /* Some platforms specify that the chdir call may be
914 interrupted. Repeat the call until it finishes. */
915 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
916 free(cp->RealWorkingDirectory);
917 cp->RealWorkingDirectory = 0;
920 /* All the pipes are now open. */
921 cp->PipesLeft = KWSYSPE_PIPE_COUNT;
923 /* The process has now started. */
924 cp->State = kwsysProcess_State_Executing;
925 cp->Detached = cp->OptionDetach;
928 /*--------------------------------------------------------------------------*/
929 kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
931 /* Make sure a detached child process is running. */
932 if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
933 cp->TimeoutExpired || cp->Killed)
938 /* Close all the pipes safely. */
939 kwsysProcessClosePipes(cp);
941 /* We will not wait for exit, so cleanup now. */
942 kwsysProcessCleanup(cp, 0);
944 /* The process has been disowned. */
945 cp->State = kwsysProcess_State_Disowned;
948 /*--------------------------------------------------------------------------*/
949 typedef struct kwsysProcessWaitData_s
955 kwsysProcessTime TimeoutTime;
956 } kwsysProcessWaitData;
957 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
958 kwsysProcessWaitData* wd);
960 /*--------------------------------------------------------------------------*/
961 int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
964 kwsysProcessTime userStartTime = {0, 0};
965 kwsysProcessWaitData wd =
968 kwsysProcess_Pipe_None,
973 wd.UserTimeout = userTimeout;
974 /* Make sure we are executing a process. */
975 if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
978 return kwsysProcess_Pipe_None;
981 /* Record the time at which user timeout period starts. */
984 userStartTime = kwsysProcessTimeGetCurrent();
987 /* Calculate the time at which a timeout will expire, and whether it
988 is the user or process timeout. */
989 wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
992 /* Data can only be available when pipes are open. If the process
993 is not running, cp->PipesLeft will be 0. */
994 while(cp->PipesLeft > 0 &&
995 !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
997 /* Update the user timeout. */
1000 kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
1001 kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
1003 double d = kwsysProcessTimeToDouble(difference);
1005 if(*userTimeout < 0)
1011 /* Check what happened. */
1014 /* Data are ready on a pipe. */
1019 /* A timeout has expired. */
1022 /* The user timeout has expired. It has no time left. */
1023 return kwsysProcess_Pipe_Timeout;
1027 /* The process timeout has expired. Kill the children now. */
1028 kwsysProcess_Kill(cp);
1030 cp->TimeoutExpired = 1;
1031 return kwsysProcess_Pipe_None;
1036 /* No pipes are left open. */
1037 return kwsysProcess_Pipe_None;
1041 /*--------------------------------------------------------------------------*/
1042 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
1043 kwsysProcessWaitData* wd)
1046 kwsysProcessTimeNative timeoutLength;
1048 #if KWSYSPE_USE_SELECT
1051 kwsysProcessTimeNative* timeout = 0;
1053 /* Check for any open pipes with data reported ready by the last
1054 call to select. According to "man select_tut" we must deal
1055 with all descriptors reported by a call to select before
1056 passing them to another select call. */
1057 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1059 if(cp->PipeReadEnds[i] >= 0 &&
1060 FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1062 kwsysProcess_ssize_t n;
1064 /* We are handling this pipe now. Remove it from the set. */
1065 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1067 /* The pipe is ready to read without blocking. Keep trying to
1068 read until the operation is not interrupted. */
1069 while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
1070 KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
1073 /* We have data on this pipe. */
1074 if(i == KWSYSPE_PIPE_SIGNAL)
1076 /* A child process has terminated. */
1077 kwsysProcessDestroy(cp);
1079 else if(data && length)
1081 /* Report this data. */
1082 *data = cp->PipeBuffer;
1086 case KWSYSPE_PIPE_STDOUT:
1087 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1088 case KWSYSPE_PIPE_STDERR:
1089 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1094 else if(n < 0 && errno == EAGAIN)
1096 /* No data are really ready. The select call lied. See the
1097 "man select" page on Linux for cases when this occurs. */
1101 /* We are done reading from this pipe. */
1102 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1108 /* If we have data, break early. */
1114 /* Make sure the set is empty (it should always be empty here
1116 FD_ZERO(&cp->PipeSet);
1118 /* Setup a timeout if required. */
1119 if(wd->TimeoutTime.tv_sec < 0)
1125 timeout = &timeoutLength;
1127 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
1128 wd->User?wd->UserTimeout:0,
1131 /* Timeout has already expired. */
1136 /* Add the pipe reading ends that are still open. */
1138 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1140 if(cp->PipeReadEnds[i] >= 0)
1142 FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
1143 if(cp->PipeReadEnds[i] > max)
1145 max = cp->PipeReadEnds[i];
1150 /* Make sure we have a non-empty set. */
1153 /* All pipes have closed. Child has terminated. */
1157 /* Run select to block until data are available. Repeat call
1158 until it is not interrupted. */
1159 while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
1162 /* Check result of select. */
1165 /* Select's timeout expired. */
1169 else if(numReady < 0)
1171 /* Select returned an error. Leave the error description in the
1173 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1175 /* Kill the children now. */
1176 kwsysProcess_Kill(cp);
1178 cp->SelectError = 1;
1183 /* Poll pipes for data since we do not have select. */
1184 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1186 if(cp->PipeReadEnds[i] >= 0)
1188 const int fd = cp->PipeReadEnds[i];
1189 int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
1192 /* We have data on this pipe. */
1193 if(i == KWSYSPE_PIPE_SIGNAL)
1195 /* A child process has terminated. */
1196 kwsysProcessDestroy(cp);
1198 else if(data && length)
1200 /* Report this data. */
1201 *data = cp->PipeBuffer;
1205 case KWSYSPE_PIPE_STDOUT:
1206 wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1207 case KWSYSPE_PIPE_STDERR:
1208 wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1213 else if (n == 0) /* EOF */
1215 /* We are done reading from this pipe. */
1217 if(!cp->CommandsLeft)
1220 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1224 else if (n < 0) /* error */
1227 if(!cp->CommandsLeft)
1229 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1234 if((errno != EINTR) && (errno != EAGAIN))
1236 strncpy(cp->ErrorMessage,strerror(errno),
1237 KWSYSPE_PIPE_BUFFER_SIZE);
1238 /* Kill the children now. */
1239 kwsysProcess_Kill(cp);
1241 cp->SelectError = 1;
1248 /* If we have data, break early. */
1254 if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
1257 /* Timeout has already expired. */
1262 /* Sleep a little, try again. */
1264 unsigned int msec = ((timeoutLength.tv_sec * 1000) +
1265 (timeoutLength.tv_usec / 1000));
1268 msec = 100000; /* do not sleep more than 100 milliseconds at a time */
1270 kwsysProcess_usleep(msec);
1276 /*--------------------------------------------------------------------------*/
1277 int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
1282 /* Make sure we are executing a process. */
1283 if(!cp || cp->State != kwsysProcess_State_Executing)
1288 /* Wait for all the pipes to close. Ignore all data. */
1289 while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
1291 if(prPipe == kwsysProcess_Pipe_Timeout)
1297 /* Check if there was an error in one of the waitpid calls. */
1298 if(cp->State == kwsysProcess_State_Error)
1300 /* The error message is already in its buffer. Tell
1301 kwsysProcessCleanup to not create it. */
1302 kwsysProcessCleanup(cp, 0);
1306 /* Check whether the child reported an error invoking the process. */
1309 /* The error message is already in its buffer. Tell
1310 kwsysProcessCleanup to not create it. */
1311 kwsysProcessCleanup(cp, 0);
1312 cp->State = kwsysProcess_State_Error;
1316 /* Use the status of the last process in the pipeline. */
1317 status = cp->CommandExitCodes[cp->NumberOfCommands-1];
1319 /* Determine the outcome. */
1322 /* We killed the child. */
1323 cp->State = kwsysProcess_State_Killed;
1325 else if(cp->TimeoutExpired)
1327 /* The timeout expired. */
1328 cp->State = kwsysProcess_State_Expired;
1330 else if(WIFEXITED(status))
1332 /* The child exited normally. */
1333 cp->State = kwsysProcess_State_Exited;
1334 cp->ExitException = kwsysProcess_Exception_None;
1335 cp->ExitCode = status;
1336 cp->ExitValue = (int)WEXITSTATUS(status);
1338 else if(WIFSIGNALED(status))
1340 /* The child received an unhandled signal. */
1341 cp->State = kwsysProcess_State_Exception;
1342 cp->ExitCode = status;
1343 kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
1347 /* Error getting the child return code. */
1348 strcpy(cp->ErrorMessage, "Error getting child return code.");
1349 cp->State = kwsysProcess_State_Error;
1352 /* Normal cleanup. */
1353 kwsysProcessCleanup(cp, 0);
1357 /*--------------------------------------------------------------------------*/
1358 void kwsysProcess_Kill(kwsysProcess* cp)
1362 /* Make sure we are executing a process. */
1363 if(!cp || cp->State != kwsysProcess_State_Executing)
1368 /* First close the child exit report pipe write end to avoid causing a
1369 SIGPIPE when the child terminates and our signal handler tries to
1370 report it after we have already closed the read end. */
1371 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1373 #if !defined(__APPLE__)
1374 /* Close all the pipe read ends. Do this before killing the
1375 children because Cygwin has problems killing processes that are
1376 blocking to wait for writing to their output pipes. */
1377 kwsysProcessClosePipes(cp);
1380 /* Kill the children. */
1382 for(i=0; i < cp->NumberOfCommands; ++i)
1387 /* Kill the child. */
1388 kwsysProcessKill(cp->ForkPIDs[i]);
1390 /* Reap the child. Keep trying until the call is not
1392 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
1396 #if defined(__APPLE__)
1397 /* Close all the pipe read ends. Do this after killing the
1398 children because OS X has problems closing pipe read ends whose
1399 pipes are full and still have an open write end. */
1400 kwsysProcessClosePipes(cp);
1403 cp->CommandsLeft = 0;
1406 /*--------------------------------------------------------------------------*/
1407 /* Initialize a process control structure for kwsysProcess_Execute. */
1408 static int kwsysProcessInitialize(kwsysProcess* cp)
1411 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1413 cp->PipeReadEnds[i] = -1;
1415 cp->SignalPipe = -1;
1416 cp->SelectError = 0;
1417 cp->StartTime.tv_sec = -1;
1418 cp->StartTime.tv_usec = -1;
1419 cp->TimeoutTime.tv_sec = -1;
1420 cp->TimeoutTime.tv_usec = -1;
1421 cp->TimeoutExpired = 0;
1423 cp->CommandsLeft = 0;
1424 #if KWSYSPE_USE_SELECT
1425 FD_ZERO(&cp->PipeSet);
1427 cp->State = kwsysProcess_State_Starting;
1429 cp->ExitException = kwsysProcess_Exception_None;
1432 cp->ErrorMessage[0] = 0;
1433 strcpy(cp->ExitExceptionString, "No exception");
1439 cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
1444 memset(cp->ForkPIDs, 0, sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
1446 if(cp->CommandExitCodes)
1448 free(cp->CommandExitCodes);
1450 cp->CommandExitCodes = (int*)malloc(sizeof(int)*
1451 (size_t)(cp->NumberOfCommands));
1452 if(!cp->CommandExitCodes)
1456 memset(cp->CommandExitCodes, 0, sizeof(int)*(size_t)(cp->NumberOfCommands));
1458 /* Allocate memory to save the real working directory. */
1459 if ( cp->WorkingDirectory )
1461 #if defined(MAXPATHLEN)
1462 cp->RealWorkingDirectoryLength = MAXPATHLEN;
1463 #elif defined(PATH_MAX)
1464 cp->RealWorkingDirectoryLength = PATH_MAX;
1466 cp->RealWorkingDirectoryLength = 4096;
1468 cp->RealWorkingDirectory =
1469 malloc((size_t)(cp->RealWorkingDirectoryLength));
1470 if(!cp->RealWorkingDirectory)
1479 /*--------------------------------------------------------------------------*/
1480 /* Free all resources used by the given kwsysProcess instance that were
1481 allocated by kwsysProcess_Execute. */
1482 static void kwsysProcessCleanup(kwsysProcess* cp, int error)
1488 /* We are cleaning up due to an error. Report the error message
1489 if one has not been provided already. */
1490 if(cp->ErrorMessage[0] == 0)
1492 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1495 /* Set the error state. */
1496 cp->State = kwsysProcess_State_Error;
1498 /* Kill any children already started. */
1502 for(i=0; i < cp->NumberOfCommands; ++i)
1506 /* Kill the child. */
1507 kwsysProcessKill(cp->ForkPIDs[i]);
1509 /* Reap the child. Keep trying until the call is not
1511 while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
1517 /* Restore the working directory. */
1518 if(cp->RealWorkingDirectory)
1520 while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
1524 /* If not creating a detached child, remove this object from the
1525 global set of process objects that wish to be notified when a
1527 if(!cp->OptionDetach)
1529 kwsysProcessesRemove(cp);
1538 if(cp->RealWorkingDirectory)
1540 free(cp->RealWorkingDirectory);
1541 cp->RealWorkingDirectory = 0;
1544 /* Close pipe handles. */
1545 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1547 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1551 /*--------------------------------------------------------------------------*/
1552 /* Close the given file descriptor if it is open. Reset its value to -1. */
1553 static void kwsysProcessCleanupDescriptor(int* pfd)
1555 if(pfd && *pfd >= 0)
1557 /* Keep trying to close until it is not interrupted by a
1559 while((close(*pfd) < 0) && (errno == EINTR));
1564 /*--------------------------------------------------------------------------*/
1565 static void kwsysProcessClosePipes(kwsysProcess* cp)
1569 /* Close any pipes that are still open. */
1570 for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1572 if(cp->PipeReadEnds[i] >= 0)
1574 #if KWSYSPE_USE_SELECT
1575 /* If the pipe was reported by the last call to select, we must
1576 read from it. This is needed to satisfy the suggestions from
1577 "man select_tut" and is not needed for the polling
1578 implementation. Ignore the data. */
1579 if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1581 /* We are handling this pipe now. Remove it from the set. */
1582 FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1584 /* The pipe is ready to read without blocking. Keep trying to
1585 read until the operation is not interrupted. */
1586 while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
1587 KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
1591 /* We are done reading from this pipe. */
1592 kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1598 /*--------------------------------------------------------------------------*/
1599 static int kwsysProcessSetNonBlocking(int fd)
1601 int flags = fcntl(fd, F_GETFL);
1604 flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
1609 /*--------------------------------------------------------------------------*/
1611 int decc$set_child_standard_streams(int fd1, int fd2, int fd3);
1614 /*--------------------------------------------------------------------------*/
1615 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
1616 kwsysProcessCreateInformation* si, int* readEnd)
1618 /* Setup the process's stdin. */
1621 si->StdIn = *readEnd;
1624 else if(cp->PipeFileSTDIN)
1626 /* Open a file for the child's stdin to read. */
1627 si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
1633 /* Set close-on-exec flag on the pipe's end. */
1634 if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
1639 else if(cp->PipeSharedSTDIN)
1643 else if(cp->PipeNativeSTDIN[0] >= 0)
1645 si->StdIn = cp->PipeNativeSTDIN[0];
1647 /* Set close-on-exec flag on the pipe's ends. The read end will
1648 be dup2-ed into the stdin descriptor after the fork but before
1650 if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
1651 (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
1661 /* Setup the process's stdout. */
1663 /* Create the pipe. */
1665 if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
1672 /* Set close-on-exec flag on the pipe's ends. */
1673 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
1674 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
1680 /* Replace the stdout pipe with a file if requested. In this case
1681 the select call will report that stdout is closed immediately. */
1682 if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
1684 if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
1690 /* Replace the stdout pipe with the parent's if requested. In this
1691 case the select call will report that stderr is closed
1693 if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
1695 kwsysProcessCleanupDescriptor(&si->StdOut);
1699 /* Replace the stdout pipe with the native pipe provided if any. In
1700 this case the select call will report that stdout is closed
1702 if(prIndex == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1] >= 0)
1704 if(!kwsysProcessSetupOutputPipeNative(&si->StdOut, cp->PipeNativeSTDOUT))
1710 /* Create the error reporting pipe. */
1711 if(pipe(si->ErrorPipe) < 0)
1716 /* Set close-on-exec flag on the error pipe's write end. */
1717 if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
1722 /* Fork off a child process. */
1724 /* VMS needs vfork and execvp to be in the same function because
1725 they use setjmp/longjmp to run the child startup code in the
1726 parent! TODO: OptionDetach. */
1727 cp->ForkPIDs[prIndex] = vfork();
1729 cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
1731 if(cp->ForkPIDs[prIndex] < 0)
1736 if(cp->ForkPIDs[prIndex] == 0)
1739 /* Specify standard pipes for child process. */
1740 decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr);
1742 /* Close the read end of the error reporting pipe. */
1743 close(si->ErrorPipe[0]);
1745 /* Setup the stdin, stdout, and stderr pipes. */
1750 else if(si->StdIn < 0)
1756 dup2(si->StdOut, 1);
1760 dup2(si->StdErr, 2);
1763 /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1764 All other pipe handles will be closed when exec succeeds. */
1765 fcntl(0, F_SETFD, 0);
1766 fcntl(1, F_SETFD, 0);
1767 fcntl(2, F_SETFD, 0);
1769 /* Restore all default signal handlers. */
1770 kwsysProcessRestoreDefaultSignalHandlers();
1773 /* Execute the real process. If successful, this does not return. */
1774 execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
1775 /* TODO: What does VMS do if the child fails to start? */
1777 /* Failure. Report error to parent and terminate. */
1778 kwsysProcessChildErrorExit(si->ErrorPipe[1]);
1782 /* Restore the standard pipes of this process. */
1783 decc$set_child_standard_streams(0, 1, 2);
1786 /* A child has been created. */
1789 /* We are done with the error reporting pipe write end. */
1790 kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1792 /* Block until the child's exec call succeeds and closes the error
1793 pipe or writes data to the pipe to report an error. */
1795 kwsysProcess_ssize_t total = 0;
1796 kwsysProcess_ssize_t n = 1;
1797 /* Read the entire error message up to the length of our buffer. */
1798 while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
1800 /* Keep trying to read until the operation is not interrupted. */
1801 while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
1802 (size_t)(KWSYSPE_PIPE_BUFFER_SIZE-total))) < 0) &&
1810 /* We are done with the error reporting pipe read end. */
1811 kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1815 /* The child failed to execute the process. */
1820 /* Successfully created this child process. */
1821 if(prIndex > 0 || si->StdIn > 0)
1823 /* The parent process does not need the input pipe read end. */
1824 kwsysProcessCleanupDescriptor(&si->StdIn);
1827 /* The parent process does not need the output pipe write ends. */
1830 kwsysProcessCleanupDescriptor(&si->StdOut);
1836 /*--------------------------------------------------------------------------*/
1837 static void kwsysProcessDestroy(kwsysProcess* cp)
1839 /* A child process has terminated. Reap it if it is one handled by
1842 for(i=0; i < cp->NumberOfCommands; ++i)
1847 while(((result = waitpid(cp->ForkPIDs[i],
1848 &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
1852 /* This child has termianted. */
1853 cp->ForkPIDs[i] = 0;
1854 if(--cp->CommandsLeft == 0)
1856 /* All children have terminated. Close the signal pipe
1857 write end so that no more notifications are sent to this
1859 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1861 /* TODO: Once the children have terminated, switch
1862 WaitForData to use a non-blocking read to get the
1863 rest of the data from the pipe. This is needed when
1864 grandchildren keep the output pipes open. */
1867 else if(result < 0 && cp->State != kwsysProcess_State_Error)
1869 /* Unexpected error. Report the first time this happens. */
1870 strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1871 cp->State = kwsysProcess_State_Error;
1877 /*--------------------------------------------------------------------------*/
1878 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
1886 /* Close the existing descriptor. */
1887 kwsysProcessCleanupDescriptor(p);
1889 /* Open a file for the pipe to write. */
1890 if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
1895 /* Set close-on-exec flag on the pipe's end. */
1896 if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
1901 /* Assign the replacement descriptor. */
1906 /*--------------------------------------------------------------------------*/
1907 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
1909 /* Close the existing descriptor. */
1910 kwsysProcessCleanupDescriptor(p);
1912 /* Set close-on-exec flag on the pipe's ends. The proper end will
1913 be dup2-ed into the standard descriptor number after fork but
1915 if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
1916 (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
1921 /* Assign the replacement descriptor. */
1926 /*--------------------------------------------------------------------------*/
1927 /* Get the time at which either the process or user timeout will
1928 expire. Returns 1 if the user timeout is first, and 0 otherwise. */
1929 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
1930 kwsysProcessTime* timeoutTime)
1932 /* The first time this is called, we need to calculate the time at
1933 which the child will timeout. */
1934 if(cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0)
1936 kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
1937 cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
1940 /* Start with process timeout. */
1941 *timeoutTime = cp->TimeoutTime;
1943 /* Check if the user timeout is earlier. */
1946 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1947 kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
1948 kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
1950 if(timeoutTime->tv_sec < 0 ||
1951 kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
1953 *timeoutTime = userTimeoutTime;
1960 /*--------------------------------------------------------------------------*/
1961 /* Get the length of time before the given timeout time arrives.
1962 Returns 1 if the time has already arrived, and 0 otherwise. */
1963 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
1964 double* userTimeout,
1965 kwsysProcessTimeNative* timeoutLength,
1968 if(timeoutTime->tv_sec < 0)
1970 /* No timeout time has been requested. */
1975 /* Calculate the remaining time. */
1976 kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1977 kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
1979 if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
1981 /* Caller has explicitly requested a zero timeout. */
1982 timeLeft.tv_sec = 0;
1983 timeLeft.tv_usec = 0;
1986 if(timeLeft.tv_sec < 0 ||
1987 (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired))
1989 /* Timeout has already expired. */
1994 /* There is some time left. */
1995 timeoutLength->tv_sec = timeLeft.tv_sec;
1996 timeoutLength->tv_usec = timeLeft.tv_usec;
2002 /*--------------------------------------------------------------------------*/
2003 static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
2005 kwsysProcessTime current;
2006 kwsysProcessTimeNative current_native;
2007 gettimeofday(¤t_native, 0);
2008 current.tv_sec = (long)current_native.tv_sec;
2009 current.tv_usec = (long)current_native.tv_usec;
2013 /*--------------------------------------------------------------------------*/
2014 static double kwsysProcessTimeToDouble(kwsysProcessTime t)
2016 return (double)t.tv_sec + (double)(t.tv_usec)*0.000001;
2019 /*--------------------------------------------------------------------------*/
2020 static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
2024 t.tv_usec = (long)((d-(double)(t.tv_sec))*1000000);
2028 /*--------------------------------------------------------------------------*/
2029 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
2031 return ((in1.tv_sec < in2.tv_sec) ||
2032 ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
2035 /*--------------------------------------------------------------------------*/
2036 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
2038 kwsysProcessTime out;
2039 out.tv_sec = in1.tv_sec + in2.tv_sec;
2040 out.tv_usec = in1.tv_usec + in2.tv_usec;
2041 if(out.tv_usec > 1000000)
2043 out.tv_usec -= 1000000;
2049 /*--------------------------------------------------------------------------*/
2050 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
2052 kwsysProcessTime out;
2053 out.tv_sec = in1.tv_sec - in2.tv_sec;
2054 out.tv_usec = in1.tv_usec - in2.tv_usec;
2057 out.tv_usec += 1000000;
2063 /*--------------------------------------------------------------------------*/
2064 #define KWSYSPE_CASE(type, str) \
2065 cp->ExitException = kwsysProcess_Exception_##type; \
2066 strcpy(cp->ExitExceptionString, str)
2067 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
2072 case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
2075 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2076 case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
2080 case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
2083 case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
2086 case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
2089 case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
2092 case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
2095 case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
2098 case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
2101 case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
2104 case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
2107 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2108 case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
2112 case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
2115 case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
2118 case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
2121 case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
2124 case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
2127 case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
2128 #elif defined(SIGCLD)
2129 case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
2132 case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
2135 case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
2138 case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
2141 case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
2144 case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
2147 case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
2150 case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
2153 case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
2156 case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
2159 case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
2162 case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
2165 case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
2168 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2169 case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
2173 case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
2176 case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
2179 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2180 case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
2184 cp->ExitException = kwsysProcess_Exception_Other;
2185 sprintf(cp->ExitExceptionString, "Signal %d", sig);
2191 /*--------------------------------------------------------------------------*/
2192 /* When the child process encounters an error before its program is
2193 invoked, this is called to report the error to the parent and
2195 static void kwsysProcessChildErrorExit(int errorPipe)
2197 /* Construct the error message. */
2198 char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
2199 kwsysProcess_ssize_t result;
2200 strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
2202 /* Report the error to the parent through the special pipe. */
2203 result=write(errorPipe, buffer, strlen(buffer));
2206 /* Terminate without cleanup. */
2210 /*--------------------------------------------------------------------------*/
2211 /* Restores all signal handlers to their default values. */
2212 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2214 struct sigaction act;
2215 memset(&act, 0, sizeof(struct sigaction));
2216 act.sa_handler = SIG_DFL;
2218 sigaction(SIGHUP, &act, 0);
2221 sigaction(SIGINT, &act, 0);
2224 sigaction(SIGQUIT, &act, 0);
2227 sigaction(SIGILL, &act, 0);
2230 sigaction(SIGTRAP, &act, 0);
2233 sigaction(SIGABRT, &act, 0);
2236 sigaction(SIGIOT, &act, 0);
2239 sigaction(SIGBUS, &act, 0);
2242 sigaction(SIGFPE, &act, 0);
2245 sigaction(SIGUSR1, &act, 0);
2248 sigaction(SIGSEGV, &act, 0);
2251 sigaction(SIGUSR2, &act, 0);
2254 sigaction(SIGPIPE, &act, 0);
2257 sigaction(SIGALRM, &act, 0);
2260 sigaction(SIGTERM, &act, 0);
2263 sigaction(SIGSTKFLT, &act, 0);
2266 sigaction(SIGCLD, &act, 0);
2269 sigaction(SIGCHLD, &act, 0);
2272 sigaction(SIGCONT, &act, 0);
2275 sigaction(SIGTSTP, &act, 0);
2278 sigaction(SIGTTIN, &act, 0);
2281 sigaction(SIGTTOU, &act, 0);
2284 sigaction(SIGURG, &act, 0);
2287 sigaction(SIGXCPU, &act, 0);
2290 sigaction(SIGXFSZ, &act, 0);
2293 sigaction(SIGVTALRM, &act, 0);
2296 sigaction(SIGPROF, &act, 0);
2299 sigaction(SIGWINCH, &act, 0);
2302 sigaction(SIGPOLL, &act, 0);
2305 sigaction(SIGIO, &act, 0);
2308 sigaction(SIGPWR, &act, 0);
2311 sigaction(SIGSYS, &act, 0);
2314 sigaction(SIGUNUSED, &act, 0);
2318 /*--------------------------------------------------------------------------*/
2319 static void kwsysProcessExit(void)
2324 /*--------------------------------------------------------------------------*/
2326 static pid_t kwsysProcessFork(kwsysProcess* cp,
2327 kwsysProcessCreateInformation* si)
2329 /* Create a detached process if requested. */
2330 if(cp->OptionDetach)
2332 /* Create an intermediate process. */
2333 pid_t middle_pid = fork();
2336 /* Fork failed. Return as if we were not detaching. */
2339 else if(middle_pid == 0)
2341 /* This is the intermediate process. Create the real child. */
2342 pid_t child_pid = fork();
2345 /* This is the real child process. There is nothing to do here. */
2350 /* Use the error pipe to report the pid to the real parent. */
2351 while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
2354 /* Exit without cleanup. The parent holds all resources. */
2356 return 0; /* Never reached, but avoids SunCC warning. */
2361 /* This is the original parent process. The intermediate
2362 process will use the error pipe to report the pid of the
2366 while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
2369 /* Wait for the intermediate process to exit and clean it up. */
2370 while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
2376 /* Not creating a detached process. Use normal fork. */
2382 /*--------------------------------------------------------------------------*/
2383 /* We try to obtain process information by invoking the ps command.
2384 Here we define the command to call on each platform and the
2385 corresponding parsing format string. The parsing format should
2386 have two integers to store: the pid and then the ppid. */
2387 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) \
2388 || defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__)
2389 # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2390 # define KWSYSPE_PS_FORMAT "%d %d\n"
2391 #elif defined(__sun) && (defined(__SVR4) || defined(__svr4__)) /* Solaris */
2392 # define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid"
2393 # define KWSYSPE_PS_FORMAT "%d %d\n"
2394 #elif defined(__hpux) || defined(__sun__) || defined(__sgi) || defined(_AIX) \
2396 # define KWSYSPE_PS_COMMAND "ps -ef"
2397 # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
2398 #elif defined(__QNX__)
2399 # define KWSYSPE_PS_COMMAND "ps -Af"
2400 # define KWSYSPE_PS_FORMAT "%*d %d %d %*[^\n]\n"
2401 #elif defined(__CYGWIN__)
2402 # define KWSYSPE_PS_COMMAND "ps aux"
2403 # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
2406 /*--------------------------------------------------------------------------*/
2407 static void kwsysProcessKill(pid_t process_id)
2409 #if defined(__linux__) || defined(__CYGWIN__)
2413 /* Suspend the process to be sure it will not create more children. */
2414 kill(process_id, SIGSTOP);
2416 /* Kill all children if we can find them. */
2417 #if defined(__linux__) || defined(__CYGWIN__)
2418 /* First try using the /proc filesystem. */
2419 if((procdir = opendir("/proc")) != NULL)
2421 #if defined(MAXPATHLEN)
2422 char fname[MAXPATHLEN];
2423 #elif defined(PATH_MAX)
2424 char fname[PATH_MAX];
2428 char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
2431 /* Each process has a directory in /proc whose name is the pid.
2432 Within this directory is a file called stat that has the
2435 pid (command line) status ppid ...
2437 We want to get the ppid for all processes. Those that have
2438 process_id as their parent should be recursively killed. */
2439 for(d = readdir(procdir); d; d = readdir(procdir))
2442 if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
2445 sprintf(fname, "/proc/%d/stat", pid);
2446 if(stat(fname, &finfo) == 0)
2448 FILE* f = fopen(fname, "r");
2451 size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
2452 buffer[nread] = '\0';
2455 const char* rparen = strrchr(buffer, ')');
2457 if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
2459 if(ppid == process_id)
2461 /* Recursively kill this child and its children. */
2462 kwsysProcessKill(pid);
2476 #if defined(KWSYSPE_PS_COMMAND)
2477 /* Try running "ps" to get the process information. */
2478 FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
2480 /* Make sure the process started and provided a valid header. */
2481 if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
2483 /* Look for processes whose parent is the process being killed. */
2485 while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
2487 if(ppid == process_id)
2489 /* Recursively kill this child and its children. */
2490 kwsysProcessKill(pid);
2495 /* We are done with the ps process. */
2503 /* Kill the process. */
2504 kill(process_id, SIGKILL);
2506 #if defined(__APPLE__)
2507 /* On OS X 10.3 the above SIGSTOP occasionally prevents the SIGKILL
2508 from working. Just in case, we resume the child and kill it
2509 again. There is a small race condition in this obscure case. If
2510 the child manages to fork again between these two signals, we
2511 will not catch its children. */
2512 kill(process_id, SIGCONT);
2513 kill(process_id, SIGKILL);
2517 /*--------------------------------------------------------------------------*/
2519 int decc$feature_get_index(const char* name);
2520 int decc$feature_set_value(int index, int mode, int value);
2521 static int kwsysProcessSetVMSFeature(const char* name, int value)
2525 i = decc$feature_get_index(name);
2526 return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
2530 /*--------------------------------------------------------------------------*/
2531 /* Global set of executing processes for use by the signal handler.
2532 This global instance will be zero-initialized by the compiler. */
2533 typedef struct kwsysProcessInstances_s
2537 kwsysProcess** Processes;
2538 } kwsysProcessInstances;
2539 static kwsysProcessInstances kwsysProcesses;
2541 /* The old SIGCHLD handler. */
2542 static struct sigaction kwsysProcessesOldSigChldAction;
2544 /*--------------------------------------------------------------------------*/
2545 static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
2547 /* Block SIGCHLD while we update the set of pipes to check.
2548 TODO: sigprocmask is undefined for threaded apps. See
2552 sigemptyset(&newset);
2553 sigaddset(&newset, SIGCHLD);
2554 sigprocmask(SIG_BLOCK, &newset, &oldset);
2556 /* Store the new set in that seen by the signal handler. */
2557 kwsysProcesses = *newProcesses;
2559 /* Restore the signal mask to the previous setting. */
2560 sigprocmask(SIG_SETMASK, &oldset, 0);
2563 /*--------------------------------------------------------------------------*/
2564 static int kwsysProcessesAdd(kwsysProcess* cp)
2566 /* Create a pipe through which the signal handler can notify the
2567 given process object that a child has exited. */
2569 /* Create the pipe. */
2571 if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
2576 /* Store the pipes now to be sure they are cleaned up later. */
2577 cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
2578 cp->SignalPipe = p[1];
2580 /* Switch the pipe to non-blocking mode so that reading a byte can
2581 be an atomic test-and-set. */
2582 if(!kwsysProcessSetNonBlocking(p[0]) ||
2583 !kwsysProcessSetNonBlocking(p[1]))
2588 /* The children do not need this pipe. Set close-on-exec flag on
2590 if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
2591 (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
2597 /* Attempt to add the given signal pipe to the signal handler set. */
2600 /* Make sure there is enough space for the new signal pipe. */
2601 kwsysProcessInstances oldProcesses = kwsysProcesses;
2602 kwsysProcessInstances newProcesses = oldProcesses;
2603 if(oldProcesses.Count == oldProcesses.Size)
2605 /* Start with enough space for a small number of process instances
2606 and double the size each time more is needed. */
2607 newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
2609 /* Try allocating the new block of memory. */
2610 if((newProcesses.Processes = ((kwsysProcess**)
2611 malloc((size_t)(newProcesses.Size)*
2612 sizeof(kwsysProcess*)))))
2614 /* Copy the old pipe set to the new memory. */
2615 if(oldProcesses.Count > 0)
2617 memcpy(newProcesses.Processes, oldProcesses.Processes,
2618 ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
2623 /* Failed to allocate memory for the new signal pipe set. */
2628 /* Append the new signal pipe to the set. */
2629 newProcesses.Processes[newProcesses.Count++] = cp;
2631 /* Store the new set in that seen by the signal handler. */
2632 kwsysProcessesUpdate(&newProcesses);
2634 /* Free the original pipes if new ones were allocated. */
2635 if(newProcesses.Processes != oldProcesses.Processes)
2637 free(oldProcesses.Processes);
2640 /* If this is the first process, enable the signal handler. */
2641 if(newProcesses.Count == 1)
2643 /* Install our handler for SIGCHLD. Repeat call until it is not
2645 struct sigaction newSigChldAction;
2646 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2647 #if KWSYSPE_USE_SIGINFO
2648 newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
2649 newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2651 newSigChldAction.sa_flags |= SA_RESTART;
2654 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2655 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2657 while((sigaction(SIGCHLD, &newSigChldAction,
2658 &kwsysProcessesOldSigChldAction) < 0) &&
2666 /*--------------------------------------------------------------------------*/
2667 static void kwsysProcessesRemove(kwsysProcess* cp)
2669 /* Attempt to remove the given signal pipe from the signal handler set. */
2671 /* Find the given process in the set. */
2672 kwsysProcessInstances newProcesses = kwsysProcesses;
2674 for(i=0; i < newProcesses.Count; ++i)
2676 if(newProcesses.Processes[i] == cp)
2681 if(i < newProcesses.Count)
2683 /* Remove the process from the set. */
2684 --newProcesses.Count;
2685 for(; i < newProcesses.Count; ++i)
2687 newProcesses.Processes[i] = newProcesses.Processes[i+1];
2690 /* If this was the last process, disable the signal handler. */
2691 if(newProcesses.Count == 0)
2693 /* Restore the SIGCHLD handler. Repeat call until it is not
2695 while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
2698 /* Free the table of process pointers since it is now empty.
2699 This is safe because the signal handler has been removed. */
2700 newProcesses.Size = 0;
2701 free(newProcesses.Processes);
2702 newProcesses.Processes = 0;
2705 /* Store the new set in that seen by the signal handler. */
2706 kwsysProcessesUpdate(&newProcesses);
2710 /* Close the pipe through which the signal handler may have notified
2711 the given process object that a child has exited. */
2712 kwsysProcessCleanupDescriptor(&cp->SignalPipe);
2715 /*--------------------------------------------------------------------------*/
2716 static void kwsysProcessesSignalHandler(int signum
2717 #if KWSYSPE_USE_SIGINFO
2718 , siginfo_t* info, void* ucontext
2723 #if KWSYSPE_USE_SIGINFO
2728 /* Signal all process objects that a child has terminated. */
2731 for(i=0; i < kwsysProcesses.Count; ++i)
2733 /* Set the pipe in a signalled state. */
2735 kwsysProcess* cp = kwsysProcesses.Processes[i];
2736 kwsysProcess_ssize_t status=
2737 read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
2739 status=write(cp->SignalPipe, &buf, 1);
2744 #if !KWSYSPE_USE_SIGINFO
2745 /* Re-Install our handler for SIGCHLD. Repeat call until it is not
2748 struct sigaction newSigChldAction;
2749 memset(&newSigChldAction, 0, sizeof(struct sigaction));
2750 newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2751 newSigChldAction.sa_flags = SA_NOCLDSTOP;
2752 while((sigaction(SIGCHLD, &newSigChldAction,
2753 &kwsysProcessesOldSigChldAction) < 0) &&