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 */
70 #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
71 typedef ptrdiff_t kwsysProcess_ptrdiff_t
;
73 typedef int kwsysProcess_ptrdiff_t
;
76 #if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
77 typedef ssize_t kwsysProcess_ssize_t
;
79 typedef int kwsysProcess_ssize_t
;
82 #if defined(__BEOS__) && !defined(__ZETA__)
83 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
84 # include <be/kernel/OS.h>
85 static inline void kwsysProcess_usleep(unsigned int msec
)
90 # define kwsysProcess_usleep usleep
94 * BeOS's select() works like WinSock: it's for networking only, and
95 * doesn't work with Unix file handles...socket and file handles are
96 * different namespaces (the same descriptor means different things in
99 * So on Unix-like systems where select() is flakey, we'll set the
100 * pipes' file handles to be non-blocking and just poll them directly
103 #if !defined(__BEOS__)
104 # define KWSYSPE_USE_SELECT 1
107 /* Some platforms do not have siginfo on their signal handlers. */
108 #if defined(SA_SIGINFO) && !defined(__BEOS__)
109 # define KWSYSPE_USE_SIGINFO 1
112 /* The number of pipes for the child's output. The standard stdout
113 and stderr pipes are the first two. One more pipe is used to
114 detect when the child process has terminated. The third pipe is
115 not given to the child process, so it cannot close it until it
117 #define KWSYSPE_PIPE_COUNT 3
118 #define KWSYSPE_PIPE_STDOUT 0
119 #define KWSYSPE_PIPE_STDERR 1
120 #define KWSYSPE_PIPE_SIGNAL 2
122 /* The maximum amount to read from a pipe at a time. */
123 #define KWSYSPE_PIPE_BUFFER_SIZE 1024
125 /* Keep track of times using a signed representation. Switch to the
126 native (possibly unsigned) representation only when calling native
128 typedef struct timeval kwsysProcessTimeNative
;
129 typedef struct kwsysProcessTime_s kwsysProcessTime
;
130 struct kwsysProcessTime_s
136 typedef struct kwsysProcessCreateInformation_s
142 } kwsysProcessCreateInformation
;
144 /*--------------------------------------------------------------------------*/
145 static int kwsysProcessInitialize(kwsysProcess
* cp
);
146 static void kwsysProcessCleanup(kwsysProcess
* cp
, int error
);
147 static void kwsysProcessCleanupDescriptor(int* pfd
);
148 static void kwsysProcessClosePipes(kwsysProcess
* cp
);
149 static int kwsysProcessSetNonBlocking(int fd
);
150 static int kwsysProcessCreate(kwsysProcess
* cp
, int prIndex
,
151 kwsysProcessCreateInformation
* si
, int* readEnd
);
152 static void kwsysProcessDestroy(kwsysProcess
* cp
);
153 static int kwsysProcessSetupOutputPipeFile(int* p
, const char* name
);
154 static int kwsysProcessSetupOutputPipeNative(int* p
, int des
[2]);
155 static int kwsysProcessGetTimeoutTime(kwsysProcess
* cp
, double* userTimeout
,
156 kwsysProcessTime
* timeoutTime
);
157 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime
* timeoutTime
,
159 kwsysProcessTimeNative
* timeoutLength
);
160 static kwsysProcessTime
kwsysProcessTimeGetCurrent(void);
161 static double kwsysProcessTimeToDouble(kwsysProcessTime t
);
162 static kwsysProcessTime
kwsysProcessTimeFromDouble(double d
);
163 static int kwsysProcessTimeLess(kwsysProcessTime in1
, kwsysProcessTime in2
);
164 static kwsysProcessTime
kwsysProcessTimeAdd(kwsysProcessTime in1
, kwsysProcessTime in2
);
165 static kwsysProcessTime
kwsysProcessTimeSubtract(kwsysProcessTime in1
, kwsysProcessTime in2
);
166 static void kwsysProcessSetExitException(kwsysProcess
* cp
, int sig
);
167 static void kwsysProcessChildErrorExit(int errorPipe
);
168 static void kwsysProcessRestoreDefaultSignalHandlers(void);
169 static pid_t
kwsysProcessFork(kwsysProcess
* cp
,
170 kwsysProcessCreateInformation
* si
);
171 static void kwsysProcessKill(pid_t process_id
);
172 static int kwsysProcessesAdd(kwsysProcess
* cp
);
173 static void kwsysProcessesRemove(kwsysProcess
* cp
);
174 #if KWSYSPE_USE_SIGINFO
175 static void kwsysProcessesSignalHandler(int signum
, siginfo_t
* info
,
178 static void kwsysProcessesSignalHandler(int signum
);
180 static char** kwsysProcessParseVerbatimCommand(const char* command
);
182 /*--------------------------------------------------------------------------*/
183 /* Structure containing data used to implement the child's execution. */
184 struct kwsysProcess_s
186 /* The command lines to execute. */
188 int NumberOfCommands
;
190 /* Descriptors for the read ends of the child's output pipes and
192 int PipeReadEnds
[KWSYSPE_PIPE_COUNT
];
194 /* Write descriptor for child termination signal pipe. */
197 /* Buffer for pipe data. */
198 char PipeBuffer
[KWSYSPE_PIPE_BUFFER_SIZE
];
200 /* Process IDs returned by the calls to fork. */
203 /* Flag for whether the children were terminated by a faild select. */
206 /* The timeout length. */
209 /* The working directory for the process. */
210 char* WorkingDirectory
;
212 /* Whether to create the child as a detached process. */
215 /* Whether the child was created as a detached process. */
218 /* Whether to treat command lines as verbatim. */
221 /* Time at which the child started. Negative for no timeout. */
222 kwsysProcessTime StartTime
;
224 /* Time at which the child will timeout. Negative for no timeout. */
225 kwsysProcessTime TimeoutTime
;
227 /* Flag for whether the timeout expired. */
230 /* The number of pipes left open during execution. */
233 #if KWSYSPE_USE_SELECT
234 /* File descriptor set for call to select. */
238 /* The number of children still executing. */
241 /* The current status of the child process. */
244 /* The exceptional behavior that terminated the child process, if
248 /* The exit code of the child process. */
251 /* The exit value of the child process, if any. */
254 /* Whether the process was killed. */
257 /* Buffer for error message in case of failure. */
258 char ErrorMessage
[KWSYSPE_PIPE_BUFFER_SIZE
+1];
260 /* Description for the ExitException. */
261 char ExitExceptionString
[KWSYSPE_PIPE_BUFFER_SIZE
+1];
263 /* The exit codes of each child process in the pipeline. */
264 int* CommandExitCodes
;
266 /* Name of files to which stdin and stdout pipes are attached. */
268 char* PipeFileSTDOUT
;
269 char* PipeFileSTDERR
;
271 /* Whether each pipe is shared with the parent process. */
273 int PipeSharedSTDOUT
;
274 int PipeSharedSTDERR
;
276 /* Native pipes provided by the user. */
277 int PipeNativeSTDIN
[2];
278 int PipeNativeSTDOUT
[2];
279 int PipeNativeSTDERR
[2];
281 /* The real working directory of this process. */
282 int RealWorkingDirectoryLength
;
283 char* RealWorkingDirectory
;
286 /*--------------------------------------------------------------------------*/
287 kwsysProcess
* kwsysProcess_New(void)
289 /* Allocate a process control structure. */
290 kwsysProcess
* cp
= (kwsysProcess
*)malloc(sizeof(kwsysProcess
));
295 memset(cp
, 0, sizeof(kwsysProcess
));
297 /* Share stdin with the parent process by default. */
298 cp
->PipeSharedSTDIN
= 1;
300 /* No native pipes by default. */
301 cp
->PipeNativeSTDIN
[0] = -1;
302 cp
->PipeNativeSTDIN
[1] = -1;
303 cp
->PipeNativeSTDOUT
[0] = -1;
304 cp
->PipeNativeSTDOUT
[1] = -1;
305 cp
->PipeNativeSTDERR
[0] = -1;
306 cp
->PipeNativeSTDERR
[1] = -1;
308 /* Set initial status. */
309 cp
->State
= kwsysProcess_State_Starting
;
314 /*--------------------------------------------------------------------------*/
315 void kwsysProcess_Delete(kwsysProcess
* cp
)
317 /* Make sure we have an instance. */
323 /* If the process is executing, wait for it to finish. */
324 if(cp
->State
== kwsysProcess_State_Executing
)
328 kwsysProcess_Disown(cp
);
332 kwsysProcess_WaitForExit(cp
, 0);
337 kwsysProcess_SetCommand(cp
, 0);
338 kwsysProcess_SetWorkingDirectory(cp
, 0);
339 kwsysProcess_SetPipeFile(cp
, kwsysProcess_Pipe_STDIN
, 0);
340 kwsysProcess_SetPipeFile(cp
, kwsysProcess_Pipe_STDOUT
, 0);
341 kwsysProcess_SetPipeFile(cp
, kwsysProcess_Pipe_STDERR
, 0);
342 if(cp
->CommandExitCodes
)
344 free(cp
->CommandExitCodes
);
349 /*--------------------------------------------------------------------------*/
350 int kwsysProcess_SetCommand(kwsysProcess
* cp
, char const* const* command
)
357 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
359 char** c
= cp
->Commands
[i
];
364 free(cp
->Commands
[i
]);
366 cp
->NumberOfCommands
= 0;
374 return kwsysProcess_AddCommand(cp
, command
);
379 /*--------------------------------------------------------------------------*/
380 int kwsysProcess_AddCommand(kwsysProcess
* cp
, char const* const* command
)
382 int newNumberOfCommands
;
385 /* Make sure we have a command to add. */
386 if(!cp
|| !command
|| !*command
)
391 /* Allocate a new array for command pointers. */
392 newNumberOfCommands
= cp
->NumberOfCommands
+ 1;
394 (char***)malloc(sizeof(char**) *(size_t)(newNumberOfCommands
))))
400 /* Copy any existing commands into the new array. */
403 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
405 newCommands
[i
] = cp
->Commands
[i
];
409 /* Add the new command. */
412 /* In order to run the given command line verbatim we need to
414 newCommands
[cp
->NumberOfCommands
] =
415 kwsysProcessParseVerbatimCommand(*command
);
416 if(!newCommands
[cp
->NumberOfCommands
])
425 /* Copy each argument string individually. */
426 char const* const* c
= command
;
427 kwsysProcess_ptrdiff_t n
= 0;
428 kwsysProcess_ptrdiff_t i
= 0;
431 newCommands
[cp
->NumberOfCommands
] =
432 (char**)malloc((size_t)(n
+1)*sizeof(char*));
433 if(!newCommands
[cp
->NumberOfCommands
])
441 newCommands
[cp
->NumberOfCommands
][i
] = strdup(command
[i
]);
442 if(!newCommands
[cp
->NumberOfCommands
][i
])
452 free(newCommands
[cp
->NumberOfCommands
][i
-1]);
457 newCommands
[cp
->NumberOfCommands
][n
] = 0;
460 /* Successfully allocated new command array. Free the old array. */
462 cp
->Commands
= newCommands
;
463 cp
->NumberOfCommands
= newNumberOfCommands
;
468 /*--------------------------------------------------------------------------*/
469 void kwsysProcess_SetTimeout(kwsysProcess
* cp
, double timeout
)
475 cp
->Timeout
= timeout
;
482 /*--------------------------------------------------------------------------*/
483 int kwsysProcess_SetWorkingDirectory(kwsysProcess
* cp
, const char* dir
)
489 if(cp
->WorkingDirectory
== dir
)
493 if(cp
->WorkingDirectory
&& dir
&& strcmp(cp
->WorkingDirectory
, dir
) == 0)
497 if(cp
->WorkingDirectory
)
499 free(cp
->WorkingDirectory
);
500 cp
->WorkingDirectory
= 0;
504 cp
->WorkingDirectory
= (char*)malloc(strlen(dir
) + 1);
505 if(!cp
->WorkingDirectory
)
509 strcpy(cp
->WorkingDirectory
, dir
);
514 /*--------------------------------------------------------------------------*/
515 int kwsysProcess_SetPipeFile(kwsysProcess
* cp
, int prPipe
, const char* file
)
524 case kwsysProcess_Pipe_STDIN
: pfile
= &cp
->PipeFileSTDIN
; break;
525 case kwsysProcess_Pipe_STDOUT
: pfile
= &cp
->PipeFileSTDOUT
; break;
526 case kwsysProcess_Pipe_STDERR
: pfile
= &cp
->PipeFileSTDERR
; break;
536 *pfile
= malloc(strlen(file
)+1);
541 strcpy(*pfile
, file
);
544 /* If we are redirecting the pipe, do not share it or use a native
548 kwsysProcess_SetPipeNative(cp
, prPipe
, 0);
549 kwsysProcess_SetPipeShared(cp
, prPipe
, 0);
554 /*--------------------------------------------------------------------------*/
555 void kwsysProcess_SetPipeShared(kwsysProcess
* cp
, int prPipe
, int shared
)
564 case kwsysProcess_Pipe_STDIN
: cp
->PipeSharedSTDIN
= shared
?1:0; break;
565 case kwsysProcess_Pipe_STDOUT
: cp
->PipeSharedSTDOUT
= shared
?1:0; break;
566 case kwsysProcess_Pipe_STDERR
: cp
->PipeSharedSTDERR
= shared
?1:0; break;
570 /* If we are sharing the pipe, do not redirect it to a file or use a
574 kwsysProcess_SetPipeFile(cp
, prPipe
, 0);
575 kwsysProcess_SetPipeNative(cp
, prPipe
, 0);
579 /*--------------------------------------------------------------------------*/
580 void kwsysProcess_SetPipeNative(kwsysProcess
* cp
, int prPipe
, int p
[2])
582 int* pPipeNative
= 0;
591 case kwsysProcess_Pipe_STDIN
: pPipeNative
= cp
->PipeNativeSTDIN
; break;
592 case kwsysProcess_Pipe_STDOUT
: pPipeNative
= cp
->PipeNativeSTDOUT
; break;
593 case kwsysProcess_Pipe_STDERR
: pPipeNative
= cp
->PipeNativeSTDERR
; break;
597 /* Copy the native pipe descriptors provided. */
600 pPipeNative
[0] = p
[0];
601 pPipeNative
[1] = p
[1];
609 /* If we are using a native pipe, do not share it or redirect it to
613 kwsysProcess_SetPipeFile(cp
, prPipe
, 0);
614 kwsysProcess_SetPipeShared(cp
, prPipe
, 0);
618 /*--------------------------------------------------------------------------*/
619 int kwsysProcess_GetOption(kwsysProcess
* cp
, int optionId
)
628 case kwsysProcess_Option_Detach
: return cp
->OptionDetach
;
629 case kwsysProcess_Option_Verbatim
: return cp
->Verbatim
;
634 /*--------------------------------------------------------------------------*/
635 void kwsysProcess_SetOption(kwsysProcess
* cp
, int optionId
, int value
)
644 case kwsysProcess_Option_Detach
: cp
->OptionDetach
= value
; break;
645 case kwsysProcess_Option_Verbatim
: cp
->Verbatim
= value
; break;
650 /*--------------------------------------------------------------------------*/
651 int kwsysProcess_GetState(kwsysProcess
* cp
)
653 return cp
? cp
->State
: kwsysProcess_State_Error
;
656 /*--------------------------------------------------------------------------*/
657 int kwsysProcess_GetExitException(kwsysProcess
* cp
)
659 return cp
? cp
->ExitException
: kwsysProcess_Exception_Other
;
662 /*--------------------------------------------------------------------------*/
663 int kwsysProcess_GetExitCode(kwsysProcess
* cp
)
665 return cp
? cp
->ExitCode
: 0;
668 /*--------------------------------------------------------------------------*/
669 int kwsysProcess_GetExitValue(kwsysProcess
* cp
)
671 return cp
? cp
->ExitValue
: -1;
674 /*--------------------------------------------------------------------------*/
675 const char* kwsysProcess_GetErrorString(kwsysProcess
* cp
)
679 return "Process management structure could not be allocated";
681 else if(cp
->State
== kwsysProcess_State_Error
)
683 return cp
->ErrorMessage
;
688 /*--------------------------------------------------------------------------*/
689 const char* kwsysProcess_GetExceptionString(kwsysProcess
* cp
)
693 return "GetExceptionString called with NULL process management structure";
695 else if(cp
->State
== kwsysProcess_State_Exception
)
697 return cp
->ExitExceptionString
;
699 return "No exception";
702 /*--------------------------------------------------------------------------*/
703 void kwsysProcess_Execute(kwsysProcess
* cp
)
706 kwsysProcessCreateInformation si
= {-1, -1, -1, {-1, -1}};
708 /* Do not execute a second copy simultaneously. */
709 if(!cp
|| cp
->State
== kwsysProcess_State_Executing
)
714 /* Initialize the control structure for a new process. */
715 if(!kwsysProcessInitialize(cp
))
717 strcpy(cp
->ErrorMessage
, "Out of memory");
718 cp
->State
= kwsysProcess_State_Error
;
722 /* Save the real working directory of this process and change to
723 the working directory for the child processes. This is needed
724 to make pipe file paths evaluate correctly. */
725 if(cp
->WorkingDirectory
)
728 if(!getcwd(cp
->RealWorkingDirectory
,
729 (size_t)(cp
->RealWorkingDirectoryLength
)))
731 kwsysProcessCleanup(cp
, 1);
735 /* Some platforms specify that the chdir call may be
736 interrupted. Repeat the call until it finishes. */
737 while(((r
= chdir(cp
->WorkingDirectory
)) < 0) && (errno
== EINTR
));
740 kwsysProcessCleanup(cp
, 1);
745 /* If not running a detached child, add this object to the global
746 set of process objects that wish to be notified when a child
748 if(!cp
->OptionDetach
)
750 if(!kwsysProcessesAdd(cp
))
752 kwsysProcessCleanup(cp
, 1);
757 /* Setup the stderr pipe to be shared by all processes. */
759 /* Create the pipe. */
763 kwsysProcessCleanup(cp
, 1);
767 /* Store the pipe. */
768 cp
->PipeReadEnds
[KWSYSPE_PIPE_STDERR
] = p
[0];
771 /* Set close-on-exec flag on the pipe's ends. */
772 if((fcntl(p
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
773 (fcntl(p
[1], F_SETFD
, FD_CLOEXEC
) < 0))
775 kwsysProcessCleanup(cp
, 1);
776 kwsysProcessCleanupDescriptor(&si
.StdErr
);
780 /* Set to non-blocking in case select lies, or for the polling
782 if(!kwsysProcessSetNonBlocking(p
[0]))
784 kwsysProcessCleanup(cp
, 1);
785 kwsysProcessCleanupDescriptor(&si
.StdErr
);
790 /* Replace the stderr pipe with a file if requested. In this case
791 the select call will report that stderr is closed immediately. */
792 if(cp
->PipeFileSTDERR
)
794 if(!kwsysProcessSetupOutputPipeFile(&si
.StdErr
, cp
->PipeFileSTDERR
))
796 kwsysProcessCleanup(cp
, 1);
797 kwsysProcessCleanupDescriptor(&si
.StdErr
);
802 /* Replace the stderr pipe with the parent's if requested. In this
803 case the select call will report that stderr is closed
805 if(cp
->PipeSharedSTDERR
)
807 kwsysProcessCleanupDescriptor(&si
.StdErr
);
811 /* Replace the stderr pipe with the native pipe provided if any. In
812 this case the select call will report that stderr is closed
814 if(cp
->PipeNativeSTDERR
[1] >= 0)
816 if(!kwsysProcessSetupOutputPipeNative(&si
.StdErr
, cp
->PipeNativeSTDERR
))
818 kwsysProcessCleanup(cp
, 1);
819 kwsysProcessCleanupDescriptor(&si
.StdErr
);
824 /* The timeout period starts now. */
825 cp
->StartTime
= kwsysProcessTimeGetCurrent();
826 cp
->TimeoutTime
.tv_sec
= -1;
827 cp
->TimeoutTime
.tv_usec
= -1;
829 /* Create the pipeline of processes. */
833 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
835 if(!kwsysProcessCreate(cp
, i
, &si
, &readEnd
))
840 /* Set the output pipe of the last process to be non-blocking in
841 case select lies, or for the polling implementation. */
842 if(i
== (cp
->NumberOfCommands
-1) && !kwsysProcessSetNonBlocking(readEnd
))
849 kwsysProcessCleanup(cp
, 1);
851 /* Release resources that may have been allocated for this
852 process before an error occurred. */
853 kwsysProcessCleanupDescriptor(&readEnd
);
856 kwsysProcessCleanupDescriptor(&si
.StdIn
);
860 kwsysProcessCleanupDescriptor(&si
.StdOut
);
864 kwsysProcessCleanupDescriptor(&si
.StdErr
);
866 kwsysProcessCleanupDescriptor(&si
.ErrorPipe
[0]);
867 kwsysProcessCleanupDescriptor(&si
.ErrorPipe
[1]);
871 /* Save a handle to the output pipe for the last process. */
872 cp
->PipeReadEnds
[KWSYSPE_PIPE_STDOUT
] = readEnd
;
875 /* The parent process does not need the output pipe write ends. */
878 kwsysProcessCleanupDescriptor(&si
.StdErr
);
881 /* Restore the working directory. */
882 if(cp
->RealWorkingDirectory
)
884 /* Some platforms specify that the chdir call may be
885 interrupted. Repeat the call until it finishes. */
886 while((chdir(cp
->RealWorkingDirectory
) < 0) && (errno
== EINTR
));
887 free(cp
->RealWorkingDirectory
);
888 cp
->RealWorkingDirectory
= 0;
891 /* All the pipes are now open. */
892 cp
->PipesLeft
= KWSYSPE_PIPE_COUNT
;
894 /* The process has now started. */
895 cp
->State
= kwsysProcess_State_Executing
;
896 cp
->Detached
= cp
->OptionDetach
;
899 /*--------------------------------------------------------------------------*/
900 kwsysEXPORT
void kwsysProcess_Disown(kwsysProcess
* cp
)
902 /* Make sure a detached child process is running. */
903 if(!cp
|| !cp
->Detached
|| cp
->State
!= kwsysProcess_State_Executing
||
904 cp
->TimeoutExpired
|| cp
->Killed
)
909 /* Close all the pipes safely. */
910 kwsysProcessClosePipes(cp
);
912 /* We will not wait for exit, so cleanup now. */
913 kwsysProcessCleanup(cp
, 0);
915 /* The process has been disowned. */
916 cp
->State
= kwsysProcess_State_Disowned
;
919 /*--------------------------------------------------------------------------*/
920 typedef struct kwsysProcessWaitData_s
926 kwsysProcessTime TimeoutTime
;
927 } kwsysProcessWaitData
;
928 static int kwsysProcessWaitForPipe(kwsysProcess
* cp
, char** data
, int* length
,
929 kwsysProcessWaitData
* wd
);
931 /*--------------------------------------------------------------------------*/
932 int kwsysProcess_WaitForData(kwsysProcess
* cp
, char** data
, int* length
,
935 kwsysProcessTime userStartTime
= {0, 0};
936 kwsysProcessWaitData wd
=
939 kwsysProcess_Pipe_None
,
944 wd
.UserTimeout
= userTimeout
;
945 /* Make sure we are executing a process. */
946 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
|| cp
->Killed
||
949 return kwsysProcess_Pipe_None
;
952 /* Record the time at which user timeout period starts. */
955 userStartTime
= kwsysProcessTimeGetCurrent();
958 /* Calculate the time at which a timeout will expire, and whether it
959 is the user or process timeout. */
960 wd
.User
= kwsysProcessGetTimeoutTime(cp
, userTimeout
,
963 /* Data can only be available when pipes are open. If the process
964 is not running, cp->PipesLeft will be 0. */
965 while(cp
->PipesLeft
> 0 &&
966 !kwsysProcessWaitForPipe(cp
, data
, length
, &wd
)) {}
968 /* Update the user timeout. */
971 kwsysProcessTime userEndTime
= kwsysProcessTimeGetCurrent();
972 kwsysProcessTime difference
= kwsysProcessTimeSubtract(userEndTime
,
974 double d
= kwsysProcessTimeToDouble(difference
);
982 /* Check what happened. */
985 /* Data are ready on a pipe. */
990 /* A timeout has expired. */
993 /* The user timeout has expired. It has no time left. */
994 return kwsysProcess_Pipe_Timeout
;
998 /* The process timeout has expired. Kill the children now. */
999 kwsysProcess_Kill(cp
);
1001 cp
->TimeoutExpired
= 1;
1002 return kwsysProcess_Pipe_None
;
1007 /* No pipes are left open. */
1008 return kwsysProcess_Pipe_None
;
1012 /*--------------------------------------------------------------------------*/
1013 static int kwsysProcessWaitForPipe(kwsysProcess
* cp
, char** data
, int* length
,
1014 kwsysProcessWaitData
* wd
)
1017 kwsysProcessTimeNative timeoutLength
;
1019 #if KWSYSPE_USE_SELECT
1022 kwsysProcessTimeNative
* timeout
= 0;
1024 /* Check for any open pipes with data reported ready by the last
1025 call to select. According to "man select_tut" we must deal
1026 with all descriptors reported by a call to select before
1027 passing them to another select call. */
1028 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1030 if(cp
->PipeReadEnds
[i
] >= 0 &&
1031 FD_ISSET(cp
->PipeReadEnds
[i
], &cp
->PipeSet
))
1033 kwsysProcess_ssize_t n
;
1035 /* We are handling this pipe now. Remove it from the set. */
1036 FD_CLR(cp
->PipeReadEnds
[i
], &cp
->PipeSet
);
1038 /* The pipe is ready to read without blocking. Keep trying to
1039 read until the operation is not interrupted. */
1040 while(((n
= read(cp
->PipeReadEnds
[i
], cp
->PipeBuffer
,
1041 KWSYSPE_PIPE_BUFFER_SIZE
)) < 0) && (errno
== EINTR
));
1044 /* We have data on this pipe. */
1045 if(i
== KWSYSPE_PIPE_SIGNAL
)
1047 /* A child process has terminated. */
1048 kwsysProcessDestroy(cp
);
1050 else if(data
&& length
)
1052 /* Report this data. */
1053 *data
= cp
->PipeBuffer
;
1057 case KWSYSPE_PIPE_STDOUT
:
1058 wd
->PipeId
= kwsysProcess_Pipe_STDOUT
; break;
1059 case KWSYSPE_PIPE_STDERR
:
1060 wd
->PipeId
= kwsysProcess_Pipe_STDERR
; break;
1065 else if(n
< 0 && errno
== EAGAIN
)
1067 /* No data are really ready. The select call lied. See the
1068 "man select" page on Linux for cases when this occurs. */
1072 /* We are done reading from this pipe. */
1073 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1079 /* If we have data, break early. */
1085 /* Make sure the set is empty (it should always be empty here
1087 FD_ZERO(&cp
->PipeSet
);
1089 /* Setup a timeout if required. */
1090 if(wd
->TimeoutTime
.tv_sec
< 0)
1096 timeout
= &timeoutLength
;
1098 if(kwsysProcessGetTimeoutLeft(&wd
->TimeoutTime
,
1099 wd
->User
?wd
->UserTimeout
:0,
1102 /* Timeout has already expired. */
1107 /* Add the pipe reading ends that are still open. */
1109 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1111 if(cp
->PipeReadEnds
[i
] >= 0)
1113 FD_SET(cp
->PipeReadEnds
[i
], &cp
->PipeSet
);
1114 if(cp
->PipeReadEnds
[i
] > max
)
1116 max
= cp
->PipeReadEnds
[i
];
1121 /* Make sure we have a non-empty set. */
1124 /* All pipes have closed. Child has terminated. */
1128 /* Run select to block until data are available. Repeat call
1129 until it is not interrupted. */
1130 while(((numReady
= select(max
+1, &cp
->PipeSet
, 0, 0, timeout
)) < 0) &&
1133 /* Check result of select. */
1136 /* Select's timeout expired. */
1140 else if(numReady
< 0)
1142 /* Select returned an error. Leave the error description in the
1144 strncpy(cp
->ErrorMessage
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
1146 /* Kill the children now. */
1147 kwsysProcess_Kill(cp
);
1149 cp
->SelectError
= 1;
1154 /* Poll pipes for data since we do not have select. */
1155 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1157 if(cp
->PipeReadEnds
[i
] >= 0)
1159 const int fd
= cp
->PipeReadEnds
[i
];
1160 int n
= read(fd
, cp
->PipeBuffer
, KWSYSPE_PIPE_BUFFER_SIZE
);
1163 /* We have data on this pipe. */
1164 if(i
== KWSYSPE_PIPE_SIGNAL
)
1166 /* A child process has terminated. */
1167 kwsysProcessDestroy(cp
);
1169 else if(data
&& length
)
1171 /* Report this data. */
1172 *data
= cp
->PipeBuffer
;
1176 case KWSYSPE_PIPE_STDOUT
:
1177 wd
->PipeId
= kwsysProcess_Pipe_STDOUT
; break;
1178 case KWSYSPE_PIPE_STDERR
:
1179 wd
->PipeId
= kwsysProcess_Pipe_STDERR
; break;
1184 else if (n
== 0) /* EOF */
1186 /* We are done reading from this pipe. */
1187 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1190 else if (n
< 0) /* error */
1192 if((errno
!= EINTR
) && (errno
!= EAGAIN
))
1194 strncpy(cp
->ErrorMessage
,strerror(errno
),
1195 KWSYSPE_PIPE_BUFFER_SIZE
);
1196 /* Kill the children now. */
1197 kwsysProcess_Kill(cp
);
1199 cp
->SelectError
= 1;
1206 /* If we have data, break early. */
1212 if(kwsysProcessGetTimeoutLeft(&wd
->TimeoutTime
, wd
->User
?wd
->UserTimeout
:0,
1215 /* Timeout has already expired. */
1220 if((timeoutLength
.tv_sec
== 0) && (timeoutLength
.tv_usec
== 0))
1222 /* Timeout has already expired. */
1227 /* Sleep a little, try again. */
1229 unsigned int msec
= ((timeoutLength
.tv_sec
* 1000) +
1230 (timeoutLength
.tv_usec
/ 1000));
1233 msec
= 100000; /* do not sleep more than 100 milliseconds at a time */
1235 kwsysProcess_usleep(msec
);
1241 /*--------------------------------------------------------------------------*/
1242 int kwsysProcess_WaitForExit(kwsysProcess
* cp
, double* userTimeout
)
1247 /* Make sure we are executing a process. */
1248 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
)
1253 /* Wait for all the pipes to close. Ignore all data. */
1254 while((prPipe
= kwsysProcess_WaitForData(cp
, 0, 0, userTimeout
)) > 0)
1256 if(prPipe
== kwsysProcess_Pipe_Timeout
)
1262 /* Check if there was an error in one of the waitpid calls. */
1263 if(cp
->State
== kwsysProcess_State_Error
)
1265 /* The error message is already in its buffer. Tell
1266 kwsysProcessCleanup to not create it. */
1267 kwsysProcessCleanup(cp
, 0);
1271 /* Check whether the child reported an error invoking the process. */
1274 /* The error message is already in its buffer. Tell
1275 kwsysProcessCleanup to not create it. */
1276 kwsysProcessCleanup(cp
, 0);
1277 cp
->State
= kwsysProcess_State_Error
;
1281 /* Use the status of the last process in the pipeline. */
1282 status
= cp
->CommandExitCodes
[cp
->NumberOfCommands
-1];
1284 /* Determine the outcome. */
1287 /* We killed the child. */
1288 cp
->State
= kwsysProcess_State_Killed
;
1290 else if(cp
->TimeoutExpired
)
1292 /* The timeout expired. */
1293 cp
->State
= kwsysProcess_State_Expired
;
1295 else if(WIFEXITED(status
))
1297 /* The child exited normally. */
1298 cp
->State
= kwsysProcess_State_Exited
;
1299 cp
->ExitException
= kwsysProcess_Exception_None
;
1300 cp
->ExitCode
= status
;
1301 cp
->ExitValue
= (int)WEXITSTATUS(status
);
1303 else if(WIFSIGNALED(status
))
1305 /* The child received an unhandled signal. */
1306 cp
->State
= kwsysProcess_State_Exception
;
1307 cp
->ExitCode
= status
;
1308 kwsysProcessSetExitException(cp
, (int)WTERMSIG(status
));
1312 /* Error getting the child return code. */
1313 strcpy(cp
->ErrorMessage
, "Error getting child return code.");
1314 cp
->State
= kwsysProcess_State_Error
;
1317 /* Normal cleanup. */
1318 kwsysProcessCleanup(cp
, 0);
1322 /*--------------------------------------------------------------------------*/
1323 void kwsysProcess_Kill(kwsysProcess
* cp
)
1327 /* Make sure we are executing a process. */
1328 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
)
1333 /* First close the child exit report pipe write end to avoid causing a
1334 SIGPIPE when the child terminates and our signal handler tries to
1335 report it after we have already closed the read end. */
1336 kwsysProcessCleanupDescriptor(&cp
->SignalPipe
);
1338 #if !defined(__APPLE__)
1339 /* Close all the pipe read ends. Do this before killing the
1340 children because Cygwin has problems killing processes that are
1341 blocking to wait for writing to their output pipes. */
1342 kwsysProcessClosePipes(cp
);
1345 /* Kill the children. */
1347 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1352 /* Kill the child. */
1353 kwsysProcessKill(cp
->ForkPIDs
[i
]);
1355 /* Reap the child. Keep trying until the call is not
1357 while((waitpid(cp
->ForkPIDs
[i
], &status
, 0) < 0) && (errno
== EINTR
));
1361 #if defined(__APPLE__)
1362 /* Close all the pipe read ends. Do this after killing the
1363 children because OS X has problems closing pipe read ends whose
1364 pipes are full and still have an open write end. */
1365 kwsysProcessClosePipes(cp
);
1368 cp
->CommandsLeft
= 0;
1371 /*--------------------------------------------------------------------------*/
1372 /* Initialize a process control structure for kwsysProcess_Execute. */
1373 static int kwsysProcessInitialize(kwsysProcess
* cp
)
1376 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1378 cp
->PipeReadEnds
[i
] = -1;
1380 cp
->SignalPipe
= -1;
1381 cp
->SelectError
= 0;
1382 cp
->StartTime
.tv_sec
= -1;
1383 cp
->StartTime
.tv_usec
= -1;
1384 cp
->TimeoutTime
.tv_sec
= -1;
1385 cp
->TimeoutTime
.tv_usec
= -1;
1386 cp
->TimeoutExpired
= 0;
1388 cp
->CommandsLeft
= 0;
1389 #if KWSYSPE_USE_SELECT
1390 FD_ZERO(&cp
->PipeSet
);
1392 cp
->State
= kwsysProcess_State_Starting
;
1394 cp
->ExitException
= kwsysProcess_Exception_None
;
1397 cp
->ErrorMessage
[0] = 0;
1398 strcpy(cp
->ExitExceptionString
, "No exception");
1404 cp
->ForkPIDs
= (pid_t
*)malloc(sizeof(pid_t
)*(size_t)(cp
->NumberOfCommands
));
1409 memset(cp
->ForkPIDs
, 0, sizeof(pid_t
)*(size_t)(cp
->NumberOfCommands
));
1411 if(cp
->CommandExitCodes
)
1413 free(cp
->CommandExitCodes
);
1415 cp
->CommandExitCodes
= (int*)malloc(sizeof(int)*
1416 (size_t)(cp
->NumberOfCommands
));
1417 if(!cp
->CommandExitCodes
)
1421 memset(cp
->CommandExitCodes
, 0, sizeof(int)*(size_t)(cp
->NumberOfCommands
));
1423 /* Allocate memory to save the real working directory. */
1424 if ( cp
->WorkingDirectory
)
1426 #if defined(MAXPATHLEN)
1427 cp
->RealWorkingDirectoryLength
= MAXPATHLEN
;
1428 #elif defined(PATH_MAX)
1429 cp
->RealWorkingDirectoryLength
= PATH_MAX
;
1431 cp
->RealWorkingDirectoryLength
= 4096;
1433 cp
->RealWorkingDirectory
=
1434 malloc((size_t)(cp
->RealWorkingDirectoryLength
));
1435 if(!cp
->RealWorkingDirectory
)
1444 /*--------------------------------------------------------------------------*/
1445 /* Free all resources used by the given kwsysProcess instance that were
1446 allocated by kwsysProcess_Execute. */
1447 static void kwsysProcessCleanup(kwsysProcess
* cp
, int error
)
1453 /* We are cleaning up due to an error. Report the error message
1454 if one has not been provided already. */
1455 if(cp
->ErrorMessage
[0] == 0)
1457 strncpy(cp
->ErrorMessage
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
1460 /* Set the error state. */
1461 cp
->State
= kwsysProcess_State_Error
;
1463 /* Kill any children already started. */
1467 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1471 /* Kill the child. */
1472 kwsysProcessKill(cp
->ForkPIDs
[i
]);
1474 /* Reap the child. Keep trying until the call is not
1476 while((waitpid(cp
->ForkPIDs
[i
], &status
, 0) < 0) &&
1482 /* Restore the working directory. */
1483 if(cp
->RealWorkingDirectory
)
1485 while((chdir(cp
->RealWorkingDirectory
) < 0) && (errno
== EINTR
));
1489 /* If not creating a detached child, remove this object from the
1490 global set of process objects that wish to be notified when a
1492 if(!cp
->OptionDetach
)
1494 kwsysProcessesRemove(cp
);
1503 if(cp
->RealWorkingDirectory
)
1505 free(cp
->RealWorkingDirectory
);
1506 cp
->RealWorkingDirectory
= 0;
1509 /* Close pipe handles. */
1510 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1512 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1516 /*--------------------------------------------------------------------------*/
1517 /* Close the given file descriptor if it is open. Reset its value to -1. */
1518 static void kwsysProcessCleanupDescriptor(int* pfd
)
1520 if(pfd
&& *pfd
>= 0)
1522 /* Keep trying to close until it is not interrupted by a
1524 while((close(*pfd
) < 0) && (errno
== EINTR
));
1529 /*--------------------------------------------------------------------------*/
1530 static void kwsysProcessClosePipes(kwsysProcess
* cp
)
1534 /* Close any pipes that are still open. */
1535 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1537 if(cp
->PipeReadEnds
[i
] >= 0)
1539 #if KWSYSPE_USE_SELECT
1540 /* If the pipe was reported by the last call to select, we must
1541 read from it. This is needed to satisfy the suggestions from
1542 "man select_tut" and is not needed for the polling
1543 implementation. Ignore the data. */
1544 if(FD_ISSET(cp
->PipeReadEnds
[i
], &cp
->PipeSet
))
1546 /* We are handling this pipe now. Remove it from the set. */
1547 FD_CLR(cp
->PipeReadEnds
[i
], &cp
->PipeSet
);
1549 /* The pipe is ready to read without blocking. Keep trying to
1550 read until the operation is not interrupted. */
1551 while((read(cp
->PipeReadEnds
[i
], cp
->PipeBuffer
,
1552 KWSYSPE_PIPE_BUFFER_SIZE
) < 0) && (errno
== EINTR
));
1556 /* We are done reading from this pipe. */
1557 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1563 /*--------------------------------------------------------------------------*/
1564 static int kwsysProcessSetNonBlocking(int fd
)
1566 int flags
= fcntl(fd
, F_GETFL
);
1569 flags
= fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
);
1574 /*--------------------------------------------------------------------------*/
1575 static int kwsysProcessCreate(kwsysProcess
* cp
, int prIndex
,
1576 kwsysProcessCreateInformation
* si
, int* readEnd
)
1578 /* Setup the process's stdin. */
1581 si
->StdIn
= *readEnd
;
1584 else if(cp
->PipeFileSTDIN
)
1586 /* Open a file for the child's stdin to read. */
1587 si
->StdIn
= open(cp
->PipeFileSTDIN
, O_RDONLY
);
1593 /* Set close-on-exec flag on the pipe's end. */
1594 if(fcntl(si
->StdIn
, F_SETFD
, FD_CLOEXEC
) < 0)
1599 else if(cp
->PipeSharedSTDIN
)
1603 else if(cp
->PipeNativeSTDIN
[0] >= 0)
1605 si
->StdIn
= cp
->PipeNativeSTDIN
[0];
1607 /* Set close-on-exec flag on the pipe's ends. The read end will
1608 be dup2-ed into the stdin descriptor after the fork but before
1610 if((fcntl(cp
->PipeNativeSTDIN
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1611 (fcntl(cp
->PipeNativeSTDIN
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1621 /* Setup the process's stdout. */
1623 /* Create the pipe. */
1632 /* Set close-on-exec flag on the pipe's ends. */
1633 if((fcntl(p
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1634 (fcntl(p
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1640 /* Replace the stdout pipe with a file if requested. In this case
1641 the select call will report that stdout is closed immediately. */
1642 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeFileSTDOUT
)
1644 if(!kwsysProcessSetupOutputPipeFile(&si
->StdOut
, cp
->PipeFileSTDOUT
))
1650 /* Replace the stdout pipe with the parent's if requested. In this
1651 case the select call will report that stderr is closed
1653 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeSharedSTDOUT
)
1655 kwsysProcessCleanupDescriptor(&si
->StdOut
);
1659 /* Replace the stdout pipe with the native pipe provided if any. In
1660 this case the select call will report that stdout is closed
1662 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeNativeSTDOUT
[1] >= 0)
1664 if(!kwsysProcessSetupOutputPipeNative(&si
->StdOut
, cp
->PipeNativeSTDOUT
))
1670 /* Create the error reporting pipe. */
1671 if(pipe(si
->ErrorPipe
) < 0)
1676 /* Set close-on-exec flag on the error pipe's write end. */
1677 if(fcntl(si
->ErrorPipe
[1], F_SETFD
, FD_CLOEXEC
) < 0)
1682 /* Fork off a child process. */
1683 cp
->ForkPIDs
[prIndex
] = kwsysProcessFork(cp
, si
);
1684 if(cp
->ForkPIDs
[prIndex
] < 0)
1689 if(cp
->ForkPIDs
[prIndex
] == 0)
1691 /* Close the read end of the error reporting pipe. */
1692 close(si
->ErrorPipe
[0]);
1694 /* Setup the stdin, stdout, and stderr pipes. */
1699 else if(si
->StdIn
< 0)
1705 dup2(si
->StdOut
, 1);
1709 dup2(si
->StdErr
, 2);
1712 /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1713 All other pipe handles will be closed when exec succeeds. */
1714 fcntl(0, F_SETFD
, 0);
1715 fcntl(1, F_SETFD
, 0);
1716 fcntl(2, F_SETFD
, 0);
1718 /* Restore all default signal handlers. */
1719 kwsysProcessRestoreDefaultSignalHandlers();
1721 /* Execute the real process. If successful, this does not return. */
1722 execvp(cp
->Commands
[prIndex
][0], cp
->Commands
[prIndex
]);
1724 /* Failure. Report error to parent and terminate. */
1725 kwsysProcessChildErrorExit(si
->ErrorPipe
[1]);
1728 /* A child has been created. */
1731 /* We are done with the error reporting pipe write end. */
1732 kwsysProcessCleanupDescriptor(&si
->ErrorPipe
[1]);
1734 /* Block until the child's exec call succeeds and closes the error
1735 pipe or writes data to the pipe to report an error. */
1737 kwsysProcess_ssize_t total
= 0;
1738 kwsysProcess_ssize_t n
= 1;
1739 /* Read the entire error message up to the length of our buffer. */
1740 while(total
< KWSYSPE_PIPE_BUFFER_SIZE
&& n
> 0)
1742 /* Keep trying to read until the operation is not interrupted. */
1743 while(((n
= read(si
->ErrorPipe
[0], cp
->ErrorMessage
+total
,
1744 (size_t)(KWSYSPE_PIPE_BUFFER_SIZE
-total
))) < 0) &&
1752 /* We are done with the error reporting pipe read end. */
1753 kwsysProcessCleanupDescriptor(&si
->ErrorPipe
[0]);
1757 /* The child failed to execute the process. */
1762 /* Successfully created this child process. */
1763 if(prIndex
> 0 || si
->StdIn
> 0)
1765 /* The parent process does not need the input pipe read end. */
1766 kwsysProcessCleanupDescriptor(&si
->StdIn
);
1769 /* The parent process does not need the output pipe write ends. */
1772 kwsysProcessCleanupDescriptor(&si
->StdOut
);
1778 /*--------------------------------------------------------------------------*/
1779 static void kwsysProcessDestroy(kwsysProcess
* cp
)
1781 /* A child process has terminated. Reap it if it is one handled by
1784 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1789 while(((result
= waitpid(cp
->ForkPIDs
[i
],
1790 &cp
->CommandExitCodes
[i
], WNOHANG
)) < 0) &&
1794 /* This child has termianted. */
1795 cp
->ForkPIDs
[i
] = 0;
1796 if(--cp
->CommandsLeft
== 0)
1798 /* All children have terminated. Close the signal pipe
1799 write end so that no more notifications are sent to this
1801 kwsysProcessCleanupDescriptor(&cp
->SignalPipe
);
1803 /* TODO: Once the children have terminated, switch
1804 WaitForData to use a non-blocking read to get the
1805 rest of the data from the pipe. This is needed when
1806 grandchildren keep the output pipes open. */
1809 else if(result
< 0 && cp
->State
!= kwsysProcess_State_Error
)
1811 /* Unexpected error. Report the first time this happens. */
1812 strncpy(cp
->ErrorMessage
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
1813 cp
->State
= kwsysProcess_State_Error
;
1819 /*--------------------------------------------------------------------------*/
1820 static int kwsysProcessSetupOutputPipeFile(int* p
, const char* name
)
1828 /* Close the existing descriptor. */
1829 kwsysProcessCleanupDescriptor(p
);
1831 /* Open a file for the pipe to write (permissions 644). */
1832 if((fout
= open(name
, O_WRONLY
| O_CREAT
| O_TRUNC
,
1833 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
)) < 0)
1838 /* Set close-on-exec flag on the pipe's end. */
1839 if(fcntl(fout
, F_SETFD
, FD_CLOEXEC
) < 0)
1844 /* Assign the replacement descriptor. */
1849 /*--------------------------------------------------------------------------*/
1850 static int kwsysProcessSetupOutputPipeNative(int* p
, int des
[2])
1852 /* Close the existing descriptor. */
1853 kwsysProcessCleanupDescriptor(p
);
1855 /* Set close-on-exec flag on the pipe's ends. The proper end will
1856 be dup2-ed into the standard descriptor number after fork but
1858 if((fcntl(des
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1859 (fcntl(des
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1864 /* Assign the replacement descriptor. */
1869 /*--------------------------------------------------------------------------*/
1870 /* Get the time at which either the process or user timeout will
1871 expire. Returns 1 if the user timeout is first, and 0 otherwise. */
1872 static int kwsysProcessGetTimeoutTime(kwsysProcess
* cp
, double* userTimeout
,
1873 kwsysProcessTime
* timeoutTime
)
1875 /* The first time this is called, we need to calculate the time at
1876 which the child will timeout. */
1877 if(cp
->Timeout
&& cp
->TimeoutTime
.tv_sec
< 0)
1879 kwsysProcessTime length
= kwsysProcessTimeFromDouble(cp
->Timeout
);
1880 cp
->TimeoutTime
= kwsysProcessTimeAdd(cp
->StartTime
, length
);
1883 /* Start with process timeout. */
1884 *timeoutTime
= cp
->TimeoutTime
;
1886 /* Check if the user timeout is earlier. */
1889 kwsysProcessTime currentTime
= kwsysProcessTimeGetCurrent();
1890 kwsysProcessTime userTimeoutLength
= kwsysProcessTimeFromDouble(*userTimeout
);
1891 kwsysProcessTime userTimeoutTime
= kwsysProcessTimeAdd(currentTime
,
1893 if(timeoutTime
->tv_sec
< 0 ||
1894 kwsysProcessTimeLess(userTimeoutTime
, *timeoutTime
))
1896 *timeoutTime
= userTimeoutTime
;
1903 /*--------------------------------------------------------------------------*/
1904 /* Get the length of time before the given timeout time arrives.
1905 Returns 1 if the time has already arrived, and 0 otherwise. */
1906 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime
* timeoutTime
,
1907 double* userTimeout
,
1908 kwsysProcessTimeNative
* timeoutLength
)
1910 if(timeoutTime
->tv_sec
< 0)
1912 /* No timeout time has been requested. */
1917 /* Calculate the remaining time. */
1918 kwsysProcessTime currentTime
= kwsysProcessTimeGetCurrent();
1919 kwsysProcessTime timeLeft
= kwsysProcessTimeSubtract(*timeoutTime
,
1921 if(timeLeft
.tv_sec
< 0 && userTimeout
&& *userTimeout
<= 0)
1923 /* Caller has explicitly requested a zero timeout. */
1924 timeLeft
.tv_sec
= 0;
1925 timeLeft
.tv_usec
= 0;
1928 if(timeLeft
.tv_sec
< 0)
1930 /* Timeout has already expired. */
1935 /* There is some time left. */
1936 timeoutLength
->tv_sec
= timeLeft
.tv_sec
;
1937 timeoutLength
->tv_usec
= timeLeft
.tv_usec
;
1943 /*--------------------------------------------------------------------------*/
1944 static kwsysProcessTime
kwsysProcessTimeGetCurrent(void)
1946 kwsysProcessTime current
;
1947 kwsysProcessTimeNative current_native
;
1948 gettimeofday(¤t_native
, 0);
1949 current
.tv_sec
= (long)current_native
.tv_sec
;
1950 current
.tv_usec
= (long)current_native
.tv_usec
;
1954 /*--------------------------------------------------------------------------*/
1955 static double kwsysProcessTimeToDouble(kwsysProcessTime t
)
1957 return (double)t
.tv_sec
+ (double)(t
.tv_usec
)*0.000001;
1960 /*--------------------------------------------------------------------------*/
1961 static kwsysProcessTime
kwsysProcessTimeFromDouble(double d
)
1965 t
.tv_usec
= (long)((d
-(double)(t
.tv_sec
))*1000000);
1969 /*--------------------------------------------------------------------------*/
1970 static int kwsysProcessTimeLess(kwsysProcessTime in1
, kwsysProcessTime in2
)
1972 return ((in1
.tv_sec
< in2
.tv_sec
) ||
1973 ((in1
.tv_sec
== in2
.tv_sec
) && (in1
.tv_usec
< in2
.tv_usec
)));
1976 /*--------------------------------------------------------------------------*/
1977 static kwsysProcessTime
kwsysProcessTimeAdd(kwsysProcessTime in1
, kwsysProcessTime in2
)
1979 kwsysProcessTime out
;
1980 out
.tv_sec
= in1
.tv_sec
+ in2
.tv_sec
;
1981 out
.tv_usec
= in1
.tv_usec
+ in2
.tv_usec
;
1982 if(out
.tv_usec
> 1000000)
1984 out
.tv_usec
-= 1000000;
1990 /*--------------------------------------------------------------------------*/
1991 static kwsysProcessTime
kwsysProcessTimeSubtract(kwsysProcessTime in1
, kwsysProcessTime in2
)
1993 kwsysProcessTime out
;
1994 out
.tv_sec
= in1
.tv_sec
- in2
.tv_sec
;
1995 out
.tv_usec
= in1
.tv_usec
- in2
.tv_usec
;
1998 out
.tv_usec
+= 1000000;
2004 /*--------------------------------------------------------------------------*/
2005 #define KWSYSPE_CASE(type, str) \
2006 cp->ExitException = kwsysProcess_Exception_##type; \
2007 strcpy(cp->ExitExceptionString, str)
2008 static void kwsysProcessSetExitException(kwsysProcess
* cp
, int sig
)
2013 case SIGSEGV
: KWSYSPE_CASE(Fault
, "Segmentation fault"); break;
2016 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2017 case SIGBUS
: KWSYSPE_CASE(Fault
, "Bus error"); break;
2021 case SIGFPE
: KWSYSPE_CASE(Numerical
, "Floating-point exception"); break;
2024 case SIGILL
: KWSYSPE_CASE(Illegal
, "Illegal instruction"); break;
2027 case SIGINT
: KWSYSPE_CASE(Interrupt
, "User interrupt"); break;
2030 case SIGABRT
: KWSYSPE_CASE(Other
, "Child aborted"); break;
2033 case SIGKILL
: KWSYSPE_CASE(Other
, "Child killed"); break;
2036 case SIGTERM
: KWSYSPE_CASE(Other
, "Child terminated"); break;
2039 case SIGHUP
: KWSYSPE_CASE(Other
, "SIGHUP"); break;
2042 case SIGQUIT
: KWSYSPE_CASE(Other
, "SIGQUIT"); break;
2045 case SIGTRAP
: KWSYSPE_CASE(Other
, "SIGTRAP"); break;
2048 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2049 case SIGIOT
: KWSYSPE_CASE(Other
, "SIGIOT"); break;
2053 case SIGUSR1
: KWSYSPE_CASE(Other
, "SIGUSR1"); break;
2056 case SIGUSR2
: KWSYSPE_CASE(Other
, "SIGUSR2"); break;
2059 case SIGPIPE
: KWSYSPE_CASE(Other
, "SIGPIPE"); break;
2062 case SIGALRM
: KWSYSPE_CASE(Other
, "SIGALRM"); break;
2065 case SIGSTKFLT
: KWSYSPE_CASE(Other
, "SIGSTKFLT"); break;
2068 case SIGCHLD
: KWSYSPE_CASE(Other
, "SIGCHLD"); break;
2069 #elif defined(SIGCLD)
2070 case SIGCLD
: KWSYSPE_CASE(Other
, "SIGCLD"); break;
2073 case SIGCONT
: KWSYSPE_CASE(Other
, "SIGCONT"); break;
2076 case SIGSTOP
: KWSYSPE_CASE(Other
, "SIGSTOP"); break;
2079 case SIGTSTP
: KWSYSPE_CASE(Other
, "SIGTSTP"); break;
2082 case SIGTTIN
: KWSYSPE_CASE(Other
, "SIGTTIN"); break;
2085 case SIGTTOU
: KWSYSPE_CASE(Other
, "SIGTTOU"); break;
2088 case SIGURG
: KWSYSPE_CASE(Other
, "SIGURG"); break;
2091 case SIGXCPU
: KWSYSPE_CASE(Other
, "SIGXCPU"); break;
2094 case SIGXFSZ
: KWSYSPE_CASE(Other
, "SIGXFSZ"); break;
2097 case SIGVTALRM
: KWSYSPE_CASE(Other
, "SIGVTALRM"); break;
2100 case SIGPROF
: KWSYSPE_CASE(Other
, "SIGPROF"); break;
2103 case SIGWINCH
: KWSYSPE_CASE(Other
, "SIGWINCH"); break;
2106 case SIGPOLL
: KWSYSPE_CASE(Other
, "SIGPOLL"); break;
2109 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2110 case SIGIO
: KWSYSPE_CASE(Other
, "SIGIO"); break;
2114 case SIGPWR
: KWSYSPE_CASE(Other
, "SIGPWR"); break;
2117 case SIGSYS
: KWSYSPE_CASE(Other
, "SIGSYS"); break;
2120 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2121 case SIGUNUSED
: KWSYSPE_CASE(Other
, "SIGUNUSED"); break;
2125 cp
->ExitException
= kwsysProcess_Exception_Other
;
2126 sprintf(cp
->ExitExceptionString
, "Signal %d", sig
);
2132 /*--------------------------------------------------------------------------*/
2133 /* When the child process encounters an error before its program is
2134 invoked, this is called to report the error to the parent and
2136 static void kwsysProcessChildErrorExit(int errorPipe
)
2138 /* Construct the error message. */
2139 char buffer
[KWSYSPE_PIPE_BUFFER_SIZE
];
2140 kwsysProcess_ssize_t result
;
2141 strncpy(buffer
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
2143 /* Report the error to the parent through the special pipe. */
2144 result
=write(errorPipe
, buffer
, strlen(buffer
));
2147 /* Terminate without cleanup. */
2151 /*--------------------------------------------------------------------------*/
2152 /* Restores all signal handlers to their default values. */
2153 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2155 struct sigaction act
;
2156 memset(&act
, 0, sizeof(struct sigaction
));
2157 act
.sa_handler
= SIG_DFL
;
2159 sigaction(SIGHUP
, &act
, 0);
2162 sigaction(SIGINT
, &act
, 0);
2165 sigaction(SIGQUIT
, &act
, 0);
2168 sigaction(SIGILL
, &act
, 0);
2171 sigaction(SIGTRAP
, &act
, 0);
2174 sigaction(SIGABRT
, &act
, 0);
2177 sigaction(SIGIOT
, &act
, 0);
2180 sigaction(SIGBUS
, &act
, 0);
2183 sigaction(SIGFPE
, &act
, 0);
2186 sigaction(SIGUSR1
, &act
, 0);
2189 sigaction(SIGSEGV
, &act
, 0);
2192 sigaction(SIGUSR2
, &act
, 0);
2195 sigaction(SIGPIPE
, &act
, 0);
2198 sigaction(SIGALRM
, &act
, 0);
2201 sigaction(SIGTERM
, &act
, 0);
2204 sigaction(SIGSTKFLT
, &act
, 0);
2207 sigaction(SIGCLD
, &act
, 0);
2210 sigaction(SIGCHLD
, &act
, 0);
2213 sigaction(SIGCONT
, &act
, 0);
2216 sigaction(SIGTSTP
, &act
, 0);
2219 sigaction(SIGTTIN
, &act
, 0);
2222 sigaction(SIGTTOU
, &act
, 0);
2225 sigaction(SIGURG
, &act
, 0);
2228 sigaction(SIGXCPU
, &act
, 0);
2231 sigaction(SIGXFSZ
, &act
, 0);
2234 sigaction(SIGVTALRM
, &act
, 0);
2237 sigaction(SIGPROF
, &act
, 0);
2240 sigaction(SIGWINCH
, &act
, 0);
2243 sigaction(SIGPOLL
, &act
, 0);
2246 sigaction(SIGIO
, &act
, 0);
2249 sigaction(SIGPWR
, &act
, 0);
2252 sigaction(SIGSYS
, &act
, 0);
2255 sigaction(SIGUNUSED
, &act
, 0);
2259 /*--------------------------------------------------------------------------*/
2260 static void kwsysProcessExit(void)
2265 /*--------------------------------------------------------------------------*/
2266 static pid_t
kwsysProcessFork(kwsysProcess
* cp
,
2267 kwsysProcessCreateInformation
* si
)
2269 /* Create a detached process if requested. */
2270 if(cp
->OptionDetach
)
2272 /* Create an intermediate process. */
2273 pid_t middle_pid
= fork();
2276 /* Fork failed. Return as if we were not detaching. */
2279 else if(middle_pid
== 0)
2281 /* This is the intermediate process. Create the real child. */
2282 pid_t child_pid
= fork();
2285 /* This is the real child process. There is nothing to do here. */
2290 /* Use the error pipe to report the pid to the real parent. */
2291 while((write(si
->ErrorPipe
[1], &child_pid
, sizeof(child_pid
)) < 0) &&
2294 /* Exit without cleanup. The parent holds all resources. */
2296 return 0; /* Never reached, but avoids SunCC warning. */
2301 /* This is the original parent process. The intermediate
2302 process will use the error pipe to report the pid of the
2306 while((read(si
->ErrorPipe
[0], &child_pid
, sizeof(child_pid
)) < 0) &&
2309 /* Wait for the intermediate process to exit and clean it up. */
2310 while((waitpid(middle_pid
, &status
, 0) < 0) && (errno
== EINTR
));
2316 /* Not creating a detached process. Use normal fork. */
2321 /*--------------------------------------------------------------------------*/
2322 /* We try to obtain process information by invoking the ps command.
2323 Here we define the command to call on each platform and the
2324 corresponding parsing format string. The parsing format should
2325 have two integers to store: the pid and then the ppid. */
2326 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
2327 # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2328 # define KWSYSPE_PS_FORMAT "%d %d\n"
2329 #elif defined(__hpux) || defined(__sparc) || defined(__sgi) || defined(_AIX)
2330 # define KWSYSPE_PS_COMMAND "ps -ef"
2331 # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
2332 #elif defined(__CYGWIN__)
2333 # define KWSYSPE_PS_COMMAND "ps aux"
2334 # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
2337 /*--------------------------------------------------------------------------*/
2338 static void kwsysProcessKill(pid_t process_id
)
2340 #if defined(__linux__) || defined(__CYGWIN__)
2344 /* Kill the process now to make sure it does not create more
2345 children. Do not reap it yet so we can identify its existing
2346 children. There is a small race condition here. If the child
2347 forks after we begin looking for children below but before it
2348 receives this kill signal we might miss a child. Also we might
2349 not be able to catch up to a fork bomb. */
2350 kill(process_id
, SIGKILL
);
2352 /* Kill all children if we can find them. */
2353 #if defined(__linux__) || defined(__CYGWIN__)
2354 /* First try using the /proc filesystem. */
2355 if((procdir
= opendir("/proc")) != NULL
)
2357 #if defined(MAXPATHLEN)
2358 char fname
[MAXPATHLEN
];
2359 #elif defined(PATH_MAX)
2360 char fname
[PATH_MAX
];
2364 char buffer
[KWSYSPE_PIPE_BUFFER_SIZE
+1];
2367 /* Each process has a directory in /proc whose name is the pid.
2368 Within this directory is a file called stat that has the
2371 pid (command line) status ppid ...
2373 We want to get the ppid for all processes. Those that have
2374 process_id as their parent should be recursively killed. */
2375 for(d
= readdir(procdir
); d
; d
= readdir(procdir
))
2378 if(sscanf(d
->d_name
, "%d", &pid
) == 1 && pid
!= 0)
2381 sprintf(fname
, "/proc/%d/stat", pid
);
2382 if(stat(fname
, &finfo
) == 0)
2384 FILE* f
= fopen(fname
, "r");
2387 size_t nread
= fread(buffer
, 1, KWSYSPE_PIPE_BUFFER_SIZE
, f
);
2388 buffer
[nread
] = '\0';
2391 const char* rparen
= strrchr(buffer
, ')');
2393 if(rparen
&& (sscanf(rparen
+1, "%*s %d", &ppid
) == 1))
2395 if(ppid
== process_id
)
2397 /* Recursively kill this child and its children. */
2398 kwsysProcessKill(pid
);
2412 #if defined(KWSYSPE_PS_COMMAND)
2413 /* Try running "ps" to get the process information. */
2414 FILE* ps
= popen(KWSYSPE_PS_COMMAND
, "r");
2416 /* Make sure the process started and provided a valid header. */
2417 if(ps
&& fscanf(ps
, "%*[^\n]\n") != EOF
)
2419 /* Look for processes whose parent is the process being killed. */
2421 while(fscanf(ps
, KWSYSPE_PS_FORMAT
, &pid
, &ppid
) == 2)
2423 if(ppid
== process_id
)
2425 /* Recursively kill this child and its children. */
2426 kwsysProcessKill(pid
);
2431 /* We are done with the ps process. */
2440 /*--------------------------------------------------------------------------*/
2441 /* Global set of executing processes for use by the signal handler.
2442 This global instance will be zero-initialized by the compiler. */
2443 typedef struct kwsysProcessInstances_s
2447 kwsysProcess
** Processes
;
2448 } kwsysProcessInstances
;
2449 static kwsysProcessInstances kwsysProcesses
;
2451 /* The old SIGCHLD handler. */
2452 static struct sigaction kwsysProcessesOldSigChldAction
;
2454 /*--------------------------------------------------------------------------*/
2455 static void kwsysProcessesUpdate(kwsysProcessInstances
* newProcesses
)
2457 /* Block SIGCHLD while we update the set of pipes to check.
2458 TODO: sigprocmask is undefined for threaded apps. See
2462 sigemptyset(&newset
);
2463 sigaddset(&newset
, SIGCHLD
);
2464 sigprocmask(SIG_BLOCK
, &newset
, &oldset
);
2466 /* Store the new set in that seen by the signal handler. */
2467 kwsysProcesses
= *newProcesses
;
2469 /* Restore the signal mask to the previous setting. */
2470 sigprocmask(SIG_SETMASK
, &oldset
, 0);
2473 /*--------------------------------------------------------------------------*/
2474 static int kwsysProcessesAdd(kwsysProcess
* cp
)
2476 /* Create a pipe through which the signal handler can notify the
2477 given process object that a child has exited. */
2479 /* Create the pipe. */
2486 /* Store the pipes now to be sure they are cleaned up later. */
2487 cp
->PipeReadEnds
[KWSYSPE_PIPE_SIGNAL
] = p
[0];
2488 cp
->SignalPipe
= p
[1];
2490 /* Switch the pipe to non-blocking mode so that reading a byte can
2491 be an atomic test-and-set. */
2492 if(!kwsysProcessSetNonBlocking(p
[0]) ||
2493 !kwsysProcessSetNonBlocking(p
[1]))
2498 /* The children do not need this pipe. Set close-on-exec flag on
2500 if((fcntl(p
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
2501 (fcntl(p
[1], F_SETFD
, FD_CLOEXEC
) < 0))
2507 /* Attempt to add the given signal pipe to the signal handler set. */
2510 /* Make sure there is enough space for the new signal pipe. */
2511 kwsysProcessInstances oldProcesses
= kwsysProcesses
;
2512 kwsysProcessInstances newProcesses
= oldProcesses
;
2513 if(oldProcesses
.Count
== oldProcesses
.Size
)
2515 /* Start with enough space for a small number of process instances
2516 and double the size each time more is needed. */
2517 newProcesses
.Size
= oldProcesses
.Size
? oldProcesses
.Size
*2 : 4;
2519 /* Try allocating the new block of memory. */
2520 if((newProcesses
.Processes
= ((kwsysProcess
**)
2521 malloc((size_t)(newProcesses
.Size
)*
2522 sizeof(kwsysProcess
*)))))
2524 /* Copy the old pipe set to the new memory. */
2525 if(oldProcesses
.Count
> 0)
2527 memcpy(newProcesses
.Processes
, oldProcesses
.Processes
,
2528 ((size_t)(oldProcesses
.Count
) * sizeof(kwsysProcess
*)));
2533 /* Failed to allocate memory for the new signal pipe set. */
2538 /* Append the new signal pipe to the set. */
2539 newProcesses
.Processes
[newProcesses
.Count
++] = cp
;
2541 /* Store the new set in that seen by the signal handler. */
2542 kwsysProcessesUpdate(&newProcesses
);
2544 /* Free the original pipes if new ones were allocated. */
2545 if(newProcesses
.Processes
!= oldProcesses
.Processes
)
2547 free(oldProcesses
.Processes
);
2550 /* If this is the first process, enable the signal handler. */
2551 if(newProcesses
.Count
== 1)
2553 /* Install our handler for SIGCHLD. Repeat call until it is not
2555 struct sigaction newSigChldAction
;
2556 memset(&newSigChldAction
, 0, sizeof(struct sigaction
));
2557 #if KWSYSPE_USE_SIGINFO
2558 newSigChldAction
.sa_sigaction
= kwsysProcessesSignalHandler
;
2559 newSigChldAction
.sa_flags
= SA_NOCLDSTOP
| SA_SIGINFO
;
2561 newSigChldAction
.sa_flags
|= SA_RESTART
;
2564 newSigChldAction
.sa_handler
= kwsysProcessesSignalHandler
;
2565 newSigChldAction
.sa_flags
= SA_NOCLDSTOP
;
2567 while((sigaction(SIGCHLD
, &newSigChldAction
,
2568 &kwsysProcessesOldSigChldAction
) < 0) &&
2576 /*--------------------------------------------------------------------------*/
2577 static void kwsysProcessesRemove(kwsysProcess
* cp
)
2579 /* Attempt to remove the given signal pipe from the signal handler set. */
2581 /* Find the given process in the set. */
2582 kwsysProcessInstances newProcesses
= kwsysProcesses
;
2584 for(i
=0; i
< newProcesses
.Count
; ++i
)
2586 if(newProcesses
.Processes
[i
] == cp
)
2591 if(i
< newProcesses
.Count
)
2593 /* Remove the process from the set. */
2594 --newProcesses
.Count
;
2595 for(; i
< newProcesses
.Count
; ++i
)
2597 newProcesses
.Processes
[i
] = newProcesses
.Processes
[i
+1];
2600 /* If this was the last process, disable the signal handler. */
2601 if(newProcesses
.Count
== 0)
2603 /* Restore the SIGCHLD handler. Repeat call until it is not
2605 while((sigaction(SIGCHLD
, &kwsysProcessesOldSigChldAction
, 0) < 0) &&
2608 /* Free the table of process pointers since it is now empty.
2609 This is safe because the signal handler has been removed. */
2610 newProcesses
.Size
= 0;
2611 free(newProcesses
.Processes
);
2612 newProcesses
.Processes
= 0;
2615 /* Store the new set in that seen by the signal handler. */
2616 kwsysProcessesUpdate(&newProcesses
);
2620 /* Close the pipe through which the signal handler may have notified
2621 the given process object that a child has exited. */
2622 kwsysProcessCleanupDescriptor(&cp
->SignalPipe
);
2625 /*--------------------------------------------------------------------------*/
2626 static void kwsysProcessesSignalHandler(int signum
2627 #if KWSYSPE_USE_SIGINFO
2628 , siginfo_t
* info
, void* ucontext
2633 #if KWSYSPE_USE_SIGINFO
2638 /* Signal all process objects that a child has terminated. */
2641 for(i
=0; i
< kwsysProcesses
.Count
; ++i
)
2643 /* Set the pipe in a signalled state. */
2645 kwsysProcess
* cp
= kwsysProcesses
.Processes
[i
];
2646 kwsysProcess_ssize_t status
=
2647 read(cp
->PipeReadEnds
[KWSYSPE_PIPE_SIGNAL
], &buf
, 1);
2648 status
=write(cp
->SignalPipe
, &buf
, 1);
2653 #if !KWSYSPE_USE_SIGINFO
2654 /* Re-Install our handler for SIGCHLD. Repeat call until it is not
2657 struct sigaction newSigChldAction
;
2658 memset(&newSigChldAction
, 0, sizeof(struct sigaction
));
2659 newSigChldAction
.sa_handler
= kwsysProcessesSignalHandler
;
2660 newSigChldAction
.sa_flags
= SA_NOCLDSTOP
;
2661 while((sigaction(SIGCHLD
, &newSigChldAction
,
2662 &kwsysProcessesOldSigChldAction
) < 0) &&
2668 /*--------------------------------------------------------------------------*/
2669 static int kwsysProcessAppendByte(char* local
,
2670 char** begin
, char** end
,
2673 /* Allocate space for the character. */
2674 if((*end
- *begin
) >= *size
)
2676 kwsysProcess_ptrdiff_t length
= *end
- *begin
;
2677 char* newBuffer
= (char*)malloc((size_t)(*size
*2));
2682 memcpy(newBuffer
, *begin
, (size_t)(length
)*sizeof(char));
2688 *end
= *begin
+ length
;
2692 /* Store the character. */
2697 /*--------------------------------------------------------------------------*/
2698 static int kwsysProcessAppendArgument(char** local
,
2699 char*** begin
, char*** end
,
2702 char** arg_begin
, char** arg_end
,
2705 /* Append a null-terminator to the argument string. */
2706 if(!kwsysProcessAppendByte(arg_local
, arg_begin
, arg_end
, arg_size
, '\0'))
2711 /* Allocate space for the argument pointer. */
2712 if((*end
- *begin
) >= *size
)
2714 kwsysProcess_ptrdiff_t length
= *end
- *begin
;
2715 char** newPointers
= (char**)malloc((size_t)(*size
)*2*sizeof(char*));
2720 memcpy(newPointers
, *begin
, (size_t)(length
)*sizeof(char*));
2725 *begin
= newPointers
;
2726 *end
= *begin
+ length
;
2730 /* Allocate space for the argument string. */
2731 **end
= (char*)malloc((size_t)(*arg_end
- *arg_begin
));
2737 /* Store the argument in the command array. */
2738 memcpy(**end
, *arg_begin
,(size_t)(*arg_end
- *arg_begin
));
2741 /* Reset the argument to be empty. */
2742 *arg_end
= *arg_begin
;
2747 /*--------------------------------------------------------------------------*/
2748 #define KWSYSPE_LOCAL_BYTE_COUNT 1024
2749 #define KWSYSPE_LOCAL_ARGS_COUNT 32
2750 static char** kwsysProcessParseVerbatimCommand(const char* command
)
2752 /* Create a buffer for argument pointers during parsing. */
2753 char* local_pointers
[KWSYSPE_LOCAL_ARGS_COUNT
];
2754 int pointers_size
= KWSYSPE_LOCAL_ARGS_COUNT
;
2755 char** pointer_begin
= local_pointers
;
2756 char** pointer_end
= pointer_begin
;
2758 /* Create a buffer for argument strings during parsing. */
2759 char local_buffer
[KWSYSPE_LOCAL_BYTE_COUNT
];
2760 int buffer_size
= KWSYSPE_LOCAL_BYTE_COUNT
;
2761 char* buffer_begin
= local_buffer
;
2762 char* buffer_end
= buffer_begin
;
2764 /* Parse the command string. Try to behave like a UNIX shell. */
2765 char** newCommand
= 0;
2766 const char* c
= command
;
2767 int in_argument
= 0;
2776 /* This character is escaped so do no special handling. */
2781 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2782 &buffer_end
, &buffer_size
, *c
))
2789 else if(*c
== '\\' && !in_single
)
2791 /* The next character should be escaped. */
2794 else if(*c
== '\'' && !in_double
)
2796 /* Enter or exit single-quote state. */
2810 else if(*c
== '"' && !in_single
)
2812 /* Enter or exit double-quote state. */
2826 else if(isspace((unsigned char) *c
))
2830 if(in_single
|| in_double
)
2832 /* This space belongs to a quoted argument. */
2833 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2834 &buffer_end
, &buffer_size
, *c
))
2842 /* This argument has been terminated by whitespace. */
2843 if(!kwsysProcessAppendArgument(local_pointers
, &pointer_begin
,
2844 &pointer_end
, &pointers_size
,
2845 local_buffer
, &buffer_begin
,
2846 &buffer_end
, &buffer_size
))
2857 /* This character belong to an argument. */
2862 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2863 &buffer_end
, &buffer_size
, *c
))
2871 /* Finish the last argument. */
2874 if(!kwsysProcessAppendArgument(local_pointers
, &pointer_begin
,
2875 &pointer_end
, &pointers_size
,
2876 local_buffer
, &buffer_begin
,
2877 &buffer_end
, &buffer_size
))
2883 /* If we still have memory allocate space for the new command
2887 kwsysProcess_ptrdiff_t n
= pointer_end
- pointer_begin
;
2888 newCommand
= (char**)malloc((size_t)(n
+1)*sizeof(char*));
2893 /* Copy the arguments into the new command buffer. */
2894 kwsysProcess_ptrdiff_t n
= pointer_end
- pointer_begin
;
2895 memcpy(newCommand
, pointer_begin
, sizeof(char*)*(size_t)(n
));
2900 /* Free arguments already allocated. */
2901 while(pointer_end
!= pointer_begin
)
2903 free(*(--pointer_end
));
2907 /* Free temporary buffers. */
2908 if(pointer_begin
!= local_pointers
)
2910 free(pointer_begin
);
2912 if(buffer_begin
!= local_buffer
)
2917 /* Return the final command buffer. */