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. */
20 # include "Process.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 #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
;
69 typedef int kwsysProcess_ptrdiff_t
;
72 #if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
73 typedef ssize_t kwsysProcess_ssize_t
;
75 typedef int kwsysProcess_ssize_t
;
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
)
86 # define kwsysProcess_usleep usleep
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
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
99 #if !defined(__BEOS__)
100 # define KWSYSPE_USE_SELECT 1
103 /* Some platforms do not have siginfo on their signal handlers. */
104 #if defined(SA_SIGINFO) && !defined(__BEOS__)
105 # define KWSYSPE_USE_SIGINFO 1
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
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
124 typedef struct timeval kwsysProcessTimeNative
;
125 typedef struct kwsysProcessTime_s kwsysProcessTime
;
126 struct kwsysProcessTime_s
132 typedef struct kwsysProcessCreateInformation_s
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
,
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
,
174 static void kwsysProcessesSignalHandler(int signum
);
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. */
184 int NumberOfCommands
;
186 /* Descriptors for the read ends of the child's output pipes and
188 int PipeReadEnds
[KWSYSPE_PIPE_COUNT
];
190 /* Write descriptor for child termination signal pipe. */
193 /* Buffer for pipe data. */
194 char PipeBuffer
[KWSYSPE_PIPE_BUFFER_SIZE
];
196 /* Process IDs returned by the calls to fork. */
199 /* Flag for whether the children were terminated by a faild select. */
202 /* The timeout length. */
205 /* The working directory for the process. */
206 char* WorkingDirectory
;
208 /* Whether to create the child as a detached process. */
211 /* Whether the child was created as a detached process. */
214 /* Whether to treat command lines as 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. */
226 /* The number of pipes left open during execution. */
229 #if KWSYSPE_USE_SELECT
230 /* File descriptor set for call to select. */
234 /* The number of children still executing. */
237 /* The current status of the child process. */
240 /* The exceptional behavior that terminated the child process, if
244 /* The exit code of the child process. */
247 /* The exit value of the child process, if any. */
250 /* Whether the process was 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. */
264 char* PipeFileSTDOUT
;
265 char* PipeFileSTDERR
;
267 /* Whether each pipe is shared with the parent process. */
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
));
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
;
310 /*--------------------------------------------------------------------------*/
311 void kwsysProcess_Delete(kwsysProcess
* cp
)
313 /* Make sure we have an instance. */
319 /* If the process is executing, wait for it to finish. */
320 if(cp
->State
== kwsysProcess_State_Executing
)
324 kwsysProcess_Disown(cp
);
328 kwsysProcess_WaitForExit(cp
, 0);
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
);
345 /*--------------------------------------------------------------------------*/
346 int kwsysProcess_SetCommand(kwsysProcess
* cp
, char const* const* command
)
353 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
355 char** c
= cp
->Commands
[i
];
360 free(cp
->Commands
[i
]);
362 cp
->NumberOfCommands
= 0;
370 return kwsysProcess_AddCommand(cp
, command
);
375 /*--------------------------------------------------------------------------*/
376 int kwsysProcess_AddCommand(kwsysProcess
* cp
, char const* const* command
)
378 int newNumberOfCommands
;
381 /* Make sure we have a command to add. */
382 if(!cp
|| !command
|| !*command
)
387 /* Allocate a new array for command pointers. */
388 newNumberOfCommands
= cp
->NumberOfCommands
+ 1;
389 if(!(newCommands
= (char***)malloc(sizeof(char**) * newNumberOfCommands
)))
395 /* Copy any existing commands into the new array. */
398 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
400 newCommands
[i
] = cp
->Commands
[i
];
404 /* Add the new command. */
407 /* In order to run the given command line verbatim we need to
409 newCommands
[cp
->NumberOfCommands
] =
410 kwsysProcessParseVerbatimCommand(*command
);
411 if(!newCommands
[cp
->NumberOfCommands
])
420 /* Copy each argument string individually. */
421 char const* const* c
= command
;
422 kwsysProcess_ptrdiff_t n
= 0;
423 kwsysProcess_ptrdiff_t i
= 0;
426 newCommands
[cp
->NumberOfCommands
] = (char**)malloc((n
+1)*sizeof(char*));
427 if(!newCommands
[cp
->NumberOfCommands
])
435 newCommands
[cp
->NumberOfCommands
][i
] = strdup(command
[i
]);
436 if(!newCommands
[cp
->NumberOfCommands
][i
])
446 free(newCommands
[cp
->NumberOfCommands
][i
-1]);
451 newCommands
[cp
->NumberOfCommands
][n
] = 0;
454 /* Successfully allocated new command array. Free the old array. */
456 cp
->Commands
= newCommands
;
457 cp
->NumberOfCommands
= newNumberOfCommands
;
462 /*--------------------------------------------------------------------------*/
463 void kwsysProcess_SetTimeout(kwsysProcess
* cp
, double timeout
)
469 cp
->Timeout
= timeout
;
476 /*--------------------------------------------------------------------------*/
477 int kwsysProcess_SetWorkingDirectory(kwsysProcess
* cp
, const char* dir
)
483 if(cp
->WorkingDirectory
== dir
)
487 if(cp
->WorkingDirectory
&& dir
&& strcmp(cp
->WorkingDirectory
, dir
) == 0)
491 if(cp
->WorkingDirectory
)
493 free(cp
->WorkingDirectory
);
494 cp
->WorkingDirectory
= 0;
498 cp
->WorkingDirectory
= (char*)malloc(strlen(dir
) + 1);
499 if(!cp
->WorkingDirectory
)
503 strcpy(cp
->WorkingDirectory
, dir
);
508 /*--------------------------------------------------------------------------*/
509 int kwsysProcess_SetPipeFile(kwsysProcess
* cp
, int prPipe
, const char* file
)
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;
530 *pfile
= malloc(strlen(file
)+1);
535 strcpy(*pfile
, file
);
538 /* If we are redirecting the pipe, do not share it or use a native
542 kwsysProcess_SetPipeNative(cp
, prPipe
, 0);
543 kwsysProcess_SetPipeShared(cp
, prPipe
, 0);
548 /*--------------------------------------------------------------------------*/
549 void kwsysProcess_SetPipeShared(kwsysProcess
* cp
, int prPipe
, int shared
)
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;
564 /* If we are sharing the pipe, do not redirect it to a file or use a
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;
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;
591 /* Copy the native pipe descriptors provided. */
594 pPipeNative
[0] = p
[0];
595 pPipeNative
[1] = p
[1];
603 /* If we are using a native pipe, do not share it or redirect it to
607 kwsysProcess_SetPipeFile(cp
, prPipe
, 0);
608 kwsysProcess_SetPipeShared(cp
, prPipe
, 0);
612 /*--------------------------------------------------------------------------*/
613 int kwsysProcess_GetOption(kwsysProcess
* cp
, int optionId
)
622 case kwsysProcess_Option_Detach
: return cp
->OptionDetach
;
623 case kwsysProcess_Option_Verbatim
: return cp
->Verbatim
;
628 /*--------------------------------------------------------------------------*/
629 void kwsysProcess_SetOption(kwsysProcess
* cp
, int optionId
, int value
)
638 case kwsysProcess_Option_Detach
: cp
->OptionDetach
= value
; break;
639 case kwsysProcess_Option_Verbatim
: cp
->Verbatim
= value
; 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
)
673 return "Process management structure could not be allocated";
675 else if(cp
->State
== kwsysProcess_State_Error
)
677 return cp
->ErrorMessage
;
682 /*--------------------------------------------------------------------------*/
683 const char* kwsysProcess_GetExceptionString(kwsysProcess
* 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
)
700 kwsysProcessCreateInformation si
= {-1, -1, -1, {-1, -1}};
702 /* Do not execute a second copy simultaneously. */
703 if(!cp
|| cp
->State
== kwsysProcess_State_Executing
)
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
;
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
)
722 if(!getcwd(cp
->RealWorkingDirectory
, cp
->RealWorkingDirectoryLength
))
724 kwsysProcessCleanup(cp
, 1);
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
));
733 kwsysProcessCleanup(cp
, 1);
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
741 if(!cp
->OptionDetach
)
743 if(!kwsysProcessesAdd(cp
))
745 kwsysProcessCleanup(cp
, 1);
750 /* Setup the stderr pipe to be shared by all processes. */
752 /* Create the pipe. */
756 kwsysProcessCleanup(cp
, 1);
760 /* Store the pipe. */
761 cp
->PipeReadEnds
[KWSYSPE_PIPE_STDERR
] = p
[0];
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
);
773 #if !KWSYSPE_USE_SELECT
774 if(!kwsysProcessSetNonBlocking(p
[0]))
776 kwsysProcessCleanup(cp
, 1);
777 kwsysProcessCleanupDescriptor(&si
.StdErr
);
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
);
795 /* Replace the stderr pipe with the parent's if requested. In this
796 case the select call will report that stderr is closed
798 if(cp
->PipeSharedSTDERR
)
800 kwsysProcessCleanupDescriptor(&si
.StdErr
);
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
807 if(cp
->PipeNativeSTDERR
[1] >= 0)
809 if(!kwsysProcessSetupOutputPipeNative(&si
.StdErr
, cp
->PipeNativeSTDERR
))
811 kwsysProcessCleanup(cp
, 1);
812 kwsysProcessCleanupDescriptor(&si
.StdErr
);
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. */
826 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
828 if(!kwsysProcessCreate(cp
, i
, &si
, &readEnd
))
833 #if !KWSYSPE_USE_SELECT
834 /* Set the output pipe of the last process to be non-blocking so
836 if(i
== cp
->NumberOfCommands
-1 && !kwsysProcessSetNonBlocking(readEnd
))
844 kwsysProcessCleanup(cp
, 1);
846 /* Release resources that may have been allocated for this
847 process before an error occurred. */
848 kwsysProcessCleanupDescriptor(&readEnd
);
851 kwsysProcessCleanupDescriptor(&si
.StdIn
);
855 kwsysProcessCleanupDescriptor(&si
.StdOut
);
859 kwsysProcessCleanupDescriptor(&si
.StdErr
);
861 kwsysProcessCleanupDescriptor(&si
.ErrorPipe
[0]);
862 kwsysProcessCleanupDescriptor(&si
.ErrorPipe
[1]);
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. */
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
)
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
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
,
930 kwsysProcessTime userStartTime
= {0, 0};
931 kwsysProcessWaitData wd
=
934 kwsysProcess_Pipe_None
,
939 wd
.UserTimeout
= userTimeout
;
940 /* Make sure we are executing a process. */
941 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
|| cp
->Killed
||
944 return kwsysProcess_Pipe_None
;
947 /* Record the time at which user timeout period starts. */
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
,
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. */
966 kwsysProcessTime userEndTime
= kwsysProcessTimeGetCurrent();
967 kwsysProcessTime difference
= kwsysProcessTimeSubtract(userEndTime
,
969 double d
= kwsysProcessTimeToDouble(difference
);
977 /* Check what happened. */
980 /* Data are ready on a pipe. */
985 /* A timeout has expired. */
988 /* The user timeout has expired. It has no time left. */
989 return kwsysProcess_Pipe_Timeout
;
993 /* The process timeout has expired. Kill the children now. */
994 kwsysProcess_Kill(cp
);
996 cp
->TimeoutExpired
= 1;
997 return kwsysProcess_Pipe_None
;
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
)
1012 kwsysProcessTimeNative timeoutLength
;
1014 #if KWSYSPE_USE_SELECT
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
));
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
;
1052 case KWSYSPE_PIPE_STDOUT
:
1053 wd
->PipeId
= kwsysProcess_Pipe_STDOUT
; break;
1054 case KWSYSPE_PIPE_STDERR
:
1055 wd
->PipeId
= kwsysProcess_Pipe_STDERR
; break;
1062 /* We are done reading from this pipe. */
1063 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1069 /* If we have data, break early. */
1075 /* Make sure the set is empty (it should always be empty here
1077 FD_ZERO(&cp
->PipeSet
);
1079 /* Setup a timeout if required. */
1080 if(wd
->TimeoutTime
.tv_sec
< 0)
1086 timeout
= &timeoutLength
;
1088 if(kwsysProcessGetTimeoutLeft(&wd
->TimeoutTime
,
1089 wd
->User
?wd
->UserTimeout
:0,
1092 /* Timeout has already expired. */
1097 /* Add the pipe reading ends that are still open. */
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. */
1114 /* All pipes have closed. Child has terminated. */
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) &&
1123 /* Check result of select. */
1126 /* Select's timeout expired. */
1130 else if(numReady
< 0)
1132 /* Select returned an error. Leave the error description in the
1134 strncpy(cp
->ErrorMessage
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
1136 /* Kill the children now. */
1137 kwsysProcess_Kill(cp
);
1139 cp
->SelectError
= 1;
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
);
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
;
1166 case KWSYSPE_PIPE_STDOUT
:
1167 wd
->PipeId
= kwsysProcess_Pipe_STDOUT
; break;
1168 case KWSYSPE_PIPE_STDERR
:
1169 wd
->PipeId
= kwsysProcess_Pipe_STDERR
; break;
1174 else if (n
== 0) /* EOF */
1176 /* We are done reading from this pipe. */
1177 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
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
);
1189 cp
->SelectError
= 1;
1196 /* If we have data, break early. */
1202 if(kwsysProcessGetTimeoutLeft(&wd
->TimeoutTime
, wd
->User
?wd
->UserTimeout
:0,
1205 /* Timeout has already expired. */
1210 if((timeoutLength
.tv_sec
== 0) && (timeoutLength
.tv_usec
== 0))
1212 /* Timeout has already expired. */
1217 /* Sleep a little, try again. */
1219 unsigned int msec
= ((timeoutLength
.tv_sec
* 1000) +
1220 (timeoutLength
.tv_usec
/ 1000));
1223 msec
= 100000; /* do not sleep more than 100 milliseconds at a time */
1225 kwsysProcess_usleep(msec
);
1231 /*--------------------------------------------------------------------------*/
1232 int kwsysProcess_WaitForExit(kwsysProcess
* cp
, double* userTimeout
)
1237 /* Make sure we are executing a process. */
1238 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
)
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
)
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);
1261 /* Check whether the child reported an error invoking the process. */
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
;
1271 /* Use the status of the last process in the pipeline. */
1272 status
= cp
->CommandExitCodes
[cp
->NumberOfCommands
-1];
1274 /* Determine the outcome. */
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
));
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);
1312 /*--------------------------------------------------------------------------*/
1313 void kwsysProcess_Kill(kwsysProcess
* cp
)
1317 /* Make sure we are executing a process. */
1318 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
)
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
);
1335 /* Kill the children. */
1337 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1342 /* Kill the child. */
1343 kwsysProcessKill(cp
->ForkPIDs
[i
]);
1345 /* Reap the child. Keep trying until the call is not
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
);
1358 cp
->CommandsLeft
= 0;
1361 /*--------------------------------------------------------------------------*/
1362 /* Initialize a process control structure for kwsysProcess_Execute. */
1363 static int kwsysProcessInitialize(kwsysProcess
* cp
)
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;
1378 cp
->CommandsLeft
= 0;
1379 #if KWSYSPE_USE_SELECT
1380 FD_ZERO(&cp
->PipeSet
);
1382 cp
->State
= kwsysProcess_State_Starting
;
1384 cp
->ExitException
= kwsysProcess_Exception_None
;
1387 cp
->ErrorMessage
[0] = 0;
1388 strcpy(cp
->ExitExceptionString
, "No exception");
1394 cp
->ForkPIDs
= (pid_t
*)malloc(sizeof(pid_t
)*cp
->NumberOfCommands
);
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
)
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
;
1420 cp
->RealWorkingDirectoryLength
= 4096;
1422 cp
->RealWorkingDirectory
= malloc(cp
->RealWorkingDirectoryLength
);
1423 if(!cp
->RealWorkingDirectory
)
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
)
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. */
1455 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1459 /* Kill the child. */
1460 kwsysProcessKill(cp
->ForkPIDs
[i
]);
1462 /* Reap the child. Keep trying until the call is not
1464 while((waitpid(cp
->ForkPIDs
[i
], &status
, 0) < 0) &&
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
1480 if(!cp
->OptionDetach
)
1482 kwsysProcessesRemove(cp
);
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
1512 while((close(*pfd
) < 0) && (errno
== EINTR
));
1517 /*--------------------------------------------------------------------------*/
1518 static void kwsysProcessClosePipes(kwsysProcess
* cp
)
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
));
1544 /* We are done reading from this pipe. */
1545 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1551 /*--------------------------------------------------------------------------*/
1552 static int kwsysProcessSetNonBlocking(int fd
)
1554 int flags
= fcntl(fd
, F_GETFL
);
1557 flags
= fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
);
1562 /*--------------------------------------------------------------------------*/
1563 static int kwsysProcessCreate(kwsysProcess
* cp
, int prIndex
,
1564 kwsysProcessCreateInformation
* si
, int* readEnd
)
1566 /* Setup the process's stdin. */
1569 si
->StdIn
= *readEnd
;
1572 else if(cp
->PipeFileSTDIN
)
1574 /* Open a file for the child's stdin to read. */
1575 si
->StdIn
= open(cp
->PipeFileSTDIN
, O_RDONLY
);
1581 /* Set close-on-exec flag on the pipe's end. */
1582 if(fcntl(si
->StdIn
, F_SETFD
, FD_CLOEXEC
) < 0)
1587 else if(cp
->PipeSharedSTDIN
)
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
1598 if((fcntl(cp
->PipeNativeSTDIN
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1599 (fcntl(cp
->PipeNativeSTDIN
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1609 /* Setup the process's stdout. */
1611 /* Create the pipe. */
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))
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
))
1638 /* Replace the stdout pipe with the parent's if requested. In this
1639 case the select call will report that stderr is closed
1641 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeSharedSTDOUT
)
1643 kwsysProcessCleanupDescriptor(&si
->StdOut
);
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
1650 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeNativeSTDOUT
[1] >= 0)
1652 if(!kwsysProcessSetupOutputPipeNative(&si
->StdOut
, cp
->PipeNativeSTDOUT
))
1658 /* Create the error reporting pipe. */
1659 if(pipe(si
->ErrorPipe
) < 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)
1670 /* Fork off a child process. */
1671 cp
->ForkPIDs
[prIndex
] = kwsysProcessFork(cp
, si
);
1672 if(cp
->ForkPIDs
[prIndex
] < 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. */
1687 else if(si
->StdIn
< 0)
1693 dup2(si
->StdOut
, 1);
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. */
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) &&
1740 /* We are done with the error reporting pipe read end. */
1741 kwsysProcessCleanupDescriptor(&si
->ErrorPipe
[0]);
1745 /* The child failed to execute the process. */
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. */
1760 kwsysProcessCleanupDescriptor(&si
->StdOut
);
1766 /*--------------------------------------------------------------------------*/
1767 static void kwsysProcessDestroy(kwsysProcess
* cp
)
1769 /* A child process has terminated. Reap it if it is one handled by
1772 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1777 while(((result
= waitpid(cp
->ForkPIDs
[i
],
1778 &cp
->CommandExitCodes
[i
], WNOHANG
)) < 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
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
)
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)
1826 /* Set close-on-exec flag on the pipe's end. */
1827 if(fcntl(fout
, F_SETFD
, FD_CLOEXEC
) < 0)
1832 /* Assign the replacement descriptor. */
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
1846 if((fcntl(des
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1847 (fcntl(des
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1852 /* Assign the replacement descriptor. */
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. */
1877 kwsysProcessTime currentTime
= kwsysProcessTimeGetCurrent();
1878 kwsysProcessTime userTimeoutLength
= kwsysProcessTimeFromDouble(*userTimeout
);
1879 kwsysProcessTime userTimeoutTime
= kwsysProcessTimeAdd(currentTime
,
1881 if(timeoutTime
->tv_sec
< 0 ||
1882 kwsysProcessTimeLess(userTimeoutTime
, *timeoutTime
))
1884 *timeoutTime
= userTimeoutTime
;
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. */
1905 /* Calculate the remaining time. */
1906 kwsysProcessTime currentTime
= kwsysProcessTimeGetCurrent();
1907 kwsysProcessTime timeLeft
= kwsysProcessTimeSubtract(*timeoutTime
,
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. */
1923 /* There is some time left. */
1924 timeoutLength
->tv_sec
= timeLeft
.tv_sec
;
1925 timeoutLength
->tv_usec
= timeLeft
.tv_usec
;
1931 /*--------------------------------------------------------------------------*/
1932 static kwsysProcessTime
kwsysProcessTimeGetCurrent(void)
1934 kwsysProcessTime current
;
1935 kwsysProcessTimeNative current_native
;
1936 gettimeofday(¤t_native
, 0);
1937 current
.tv_sec
= (long)current_native
.tv_sec
;
1938 current
.tv_usec
= (long)current_native
.tv_usec
;
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
)
1953 t
.tv_usec
= (long)((d
-t
.tv_sec
)*1000000);
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;
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
;
1986 out
.tv_usec
+= 1000000;
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
)
2001 case SIGSEGV
: KWSYSPE_CASE(Fault
, "Segmentation fault"); break;
2004 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2005 case SIGBUS
: KWSYSPE_CASE(Fault
, "Bus error"); break;
2009 case SIGFPE
: KWSYSPE_CASE(Numerical
, "Floating-point exception"); break;
2012 case SIGILL
: KWSYSPE_CASE(Illegal
, "Illegal instruction"); break;
2015 case SIGINT
: KWSYSPE_CASE(Interrupt
, "User interrupt"); break;
2018 case SIGABRT
: KWSYSPE_CASE(Other
, "Child aborted"); break;
2021 case SIGKILL
: KWSYSPE_CASE(Other
, "Child killed"); break;
2024 case SIGTERM
: KWSYSPE_CASE(Other
, "Child terminated"); break;
2027 case SIGHUP
: KWSYSPE_CASE(Other
, "SIGHUP"); break;
2030 case SIGQUIT
: KWSYSPE_CASE(Other
, "SIGQUIT"); break;
2033 case SIGTRAP
: KWSYSPE_CASE(Other
, "SIGTRAP"); break;
2036 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2037 case SIGIOT
: KWSYSPE_CASE(Other
, "SIGIOT"); break;
2041 case SIGUSR1
: KWSYSPE_CASE(Other
, "SIGUSR1"); break;
2044 case SIGUSR2
: KWSYSPE_CASE(Other
, "SIGUSR2"); break;
2047 case SIGPIPE
: KWSYSPE_CASE(Other
, "SIGPIPE"); break;
2050 case SIGALRM
: KWSYSPE_CASE(Other
, "SIGALRM"); break;
2053 case SIGSTKFLT
: KWSYSPE_CASE(Other
, "SIGSTKFLT"); break;
2056 case SIGCHLD
: KWSYSPE_CASE(Other
, "SIGCHLD"); break;
2057 #elif defined(SIGCLD)
2058 case SIGCLD
: KWSYSPE_CASE(Other
, "SIGCLD"); break;
2061 case SIGCONT
: KWSYSPE_CASE(Other
, "SIGCONT"); break;
2064 case SIGSTOP
: KWSYSPE_CASE(Other
, "SIGSTOP"); break;
2067 case SIGTSTP
: KWSYSPE_CASE(Other
, "SIGTSTP"); break;
2070 case SIGTTIN
: KWSYSPE_CASE(Other
, "SIGTTIN"); break;
2073 case SIGTTOU
: KWSYSPE_CASE(Other
, "SIGTTOU"); break;
2076 case SIGURG
: KWSYSPE_CASE(Other
, "SIGURG"); break;
2079 case SIGXCPU
: KWSYSPE_CASE(Other
, "SIGXCPU"); break;
2082 case SIGXFSZ
: KWSYSPE_CASE(Other
, "SIGXFSZ"); break;
2085 case SIGVTALRM
: KWSYSPE_CASE(Other
, "SIGVTALRM"); break;
2088 case SIGPROF
: KWSYSPE_CASE(Other
, "SIGPROF"); break;
2091 case SIGWINCH
: KWSYSPE_CASE(Other
, "SIGWINCH"); break;
2094 case SIGPOLL
: KWSYSPE_CASE(Other
, "SIGPOLL"); break;
2097 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2098 case SIGIO
: KWSYSPE_CASE(Other
, "SIGIO"); break;
2102 case SIGPWR
: KWSYSPE_CASE(Other
, "SIGPWR"); break;
2105 case SIGSYS
: KWSYSPE_CASE(Other
, "SIGSYS"); break;
2108 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2109 case SIGUNUSED
: KWSYSPE_CASE(Other
, "SIGUNUSED"); break;
2113 cp
->ExitException
= kwsysProcess_Exception_Other
;
2114 sprintf(cp
->ExitExceptionString
, "Signal %d", sig
);
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
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. */
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
;
2145 sigaction(SIGHUP
, &act
, 0);
2148 sigaction(SIGINT
, &act
, 0);
2151 sigaction(SIGQUIT
, &act
, 0);
2154 sigaction(SIGILL
, &act
, 0);
2157 sigaction(SIGTRAP
, &act
, 0);
2160 sigaction(SIGABRT
, &act
, 0);
2163 sigaction(SIGIOT
, &act
, 0);
2166 sigaction(SIGBUS
, &act
, 0);
2169 sigaction(SIGFPE
, &act
, 0);
2172 sigaction(SIGUSR1
, &act
, 0);
2175 sigaction(SIGSEGV
, &act
, 0);
2178 sigaction(SIGUSR2
, &act
, 0);
2181 sigaction(SIGPIPE
, &act
, 0);
2184 sigaction(SIGALRM
, &act
, 0);
2187 sigaction(SIGTERM
, &act
, 0);
2190 sigaction(SIGSTKFLT
, &act
, 0);
2193 sigaction(SIGCLD
, &act
, 0);
2196 sigaction(SIGCHLD
, &act
, 0);
2199 sigaction(SIGCONT
, &act
, 0);
2202 sigaction(SIGTSTP
, &act
, 0);
2205 sigaction(SIGTTIN
, &act
, 0);
2208 sigaction(SIGTTOU
, &act
, 0);
2211 sigaction(SIGURG
, &act
, 0);
2214 sigaction(SIGXCPU
, &act
, 0);
2217 sigaction(SIGXFSZ
, &act
, 0);
2220 sigaction(SIGVTALRM
, &act
, 0);
2223 sigaction(SIGPROF
, &act
, 0);
2226 sigaction(SIGWINCH
, &act
, 0);
2229 sigaction(SIGPOLL
, &act
, 0);
2232 sigaction(SIGIO
, &act
, 0);
2235 sigaction(SIGPWR
, &act
, 0);
2238 sigaction(SIGSYS
, &act
, 0);
2241 sigaction(SIGUNUSED
, &act
, 0);
2245 /*--------------------------------------------------------------------------*/
2246 static void kwsysProcessExit(void)
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();
2262 /* Fork failed. Return as if we were not detaching. */
2265 else if(middle_pid
== 0)
2267 /* This is the intermediate process. Create the real child. */
2268 pid_t child_pid
= fork();
2271 /* This is the real child process. There is nothing to do here. */
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) &&
2280 /* Exit without cleanup. The parent holds all resources. */
2282 return 0; /* Never reached, but avoids SunCC warning. */
2287 /* This is the original parent process. The intermediate
2288 process will use the error pipe to report the pid of the
2292 while((read(si
->ErrorPipe
[0], &child_pid
, sizeof(child_pid
)) < 0) &&
2295 /* Wait for the intermediate process to exit and clean it up. */
2296 while((waitpid(middle_pid
, &status
, 0) < 0) && (errno
== EINTR
));
2302 /* Not creating a detached process. Use normal 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"
2323 /*--------------------------------------------------------------------------*/
2324 static void kwsysProcessKill(pid_t process_id
)
2326 #if defined(__linux__) || defined(__CYGWIN__)
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
];
2350 char buffer
[KWSYSPE_PIPE_BUFFER_SIZE
+1];
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
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
))
2364 if(sscanf(d
->d_name
, "%d", &pid
) == 1 && pid
!= 0)
2367 sprintf(fname
, "/proc/%d/stat", pid
);
2368 if(stat(fname
, &finfo
) == 0)
2370 FILE* f
= fopen(fname
, "r");
2373 int nread
= fread(buffer
, 1, KWSYSPE_PIPE_BUFFER_SIZE
, f
);
2374 buffer
[nread
] = '\0';
2377 const char* rparen
= strrchr(buffer
, ')');
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
);
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. */
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. */
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
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
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. */
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]))
2484 /* The children do not need this pipe. Set close-on-exec flag on
2486 if((fcntl(p
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
2487 (fcntl(p
[1], F_SETFD
, FD_CLOEXEC
) < 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
*)));
2519 /* Failed to allocate memory for the new signal pipe set. */
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
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
;
2547 newSigChldAction
.sa_flags
|= SA_RESTART
;
2550 newSigChldAction
.sa_handler
= kwsysProcessesSignalHandler
;
2551 newSigChldAction
.sa_flags
= SA_NOCLDSTOP
;
2553 while((sigaction(SIGCHLD
, &newSigChldAction
,
2554 &kwsysProcessesOldSigChldAction
) < 0) &&
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
;
2570 for(i
=0; i
< newProcesses
.Count
; ++i
)
2572 if(newProcesses
.Processes
[i
] == cp
)
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
2591 while((sigaction(SIGCHLD
, &kwsysProcessesOldSigChldAction
, 0) < 0) &&
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
2619 #if KWSYSPE_USE_SIGINFO
2624 /* Signal all process objects that a child has terminated. */
2627 for(i
=0; i
< kwsysProcesses
.Count
; ++i
)
2629 /* Set the pipe in a signalled state. */
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
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) &&
2652 /*--------------------------------------------------------------------------*/
2653 static int kwsysProcessAppendByte(char* local
,
2654 char** begin
, char** end
,
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);
2666 memcpy(newBuffer
, *begin
, length
*sizeof(char));
2672 *end
= *begin
+ length
;
2676 /* Store the character. */
2681 /*--------------------------------------------------------------------------*/
2682 static int kwsysProcessAppendArgument(char** local
,
2683 char*** begin
, char*** end
,
2686 char** arg_begin
, char** arg_end
,
2689 /* Append a null-terminator to the argument string. */
2690 if(!kwsysProcessAppendByte(arg_local
, arg_begin
, arg_end
, arg_size
, '\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*));
2704 memcpy(newPointers
, *begin
, length
*sizeof(char*));
2709 *begin
= newPointers
;
2710 *end
= *begin
+ length
;
2714 /* Allocate space for the argument string. */
2715 **end
= (char*)malloc(*arg_end
- *arg_begin
);
2721 /* Store the argument in the command array. */
2722 memcpy(**end
, *arg_begin
, *arg_end
- *arg_begin
);
2725 /* Reset the argument to be empty. */
2726 *arg_end
= *arg_begin
;
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;
2760 /* This character is escaped so do no special handling. */
2765 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2766 &buffer_end
, &buffer_size
, *c
))
2773 else if(*c
== '\\' && !in_single
)
2775 /* The next character should be escaped. */
2778 else if(*c
== '\'' && !in_double
)
2780 /* Enter or exit single-quote state. */
2794 else if(*c
== '"' && !in_single
)
2796 /* Enter or exit double-quote state. */
2810 else if(isspace(*c
))
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
))
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
))
2841 /* This character belong to an argument. */
2846 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2847 &buffer_end
, &buffer_size
, *c
))
2855 /* Finish the last argument. */
2858 if(!kwsysProcessAppendArgument(local_pointers
, &pointer_begin
,
2859 &pointer_end
, &pointers_size
,
2860 local_buffer
, &buffer_begin
,
2861 &buffer_end
, &buffer_size
))
2867 /* If we still have memory allocate space for the new command
2871 kwsysProcess_ptrdiff_t n
= pointer_end
- pointer_begin
;
2872 newCommand
= (char**)malloc((n
+1)*sizeof(char*));
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
);
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
)
2901 /* Return the final command buffer. */