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;
393 if(!(newCommands
= (char***)malloc(sizeof(char**) * newNumberOfCommands
)))
399 /* Copy any existing commands into the new array. */
402 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
404 newCommands
[i
] = cp
->Commands
[i
];
408 /* Add the new command. */
411 /* In order to run the given command line verbatim we need to
413 newCommands
[cp
->NumberOfCommands
] =
414 kwsysProcessParseVerbatimCommand(*command
);
415 if(!newCommands
[cp
->NumberOfCommands
])
424 /* Copy each argument string individually. */
425 char const* const* c
= command
;
426 kwsysProcess_ptrdiff_t n
= 0;
427 kwsysProcess_ptrdiff_t i
= 0;
430 newCommands
[cp
->NumberOfCommands
] = (char**)malloc((n
+1)*sizeof(char*));
431 if(!newCommands
[cp
->NumberOfCommands
])
439 newCommands
[cp
->NumberOfCommands
][i
] = strdup(command
[i
]);
440 if(!newCommands
[cp
->NumberOfCommands
][i
])
450 free(newCommands
[cp
->NumberOfCommands
][i
-1]);
455 newCommands
[cp
->NumberOfCommands
][n
] = 0;
458 /* Successfully allocated new command array. Free the old array. */
460 cp
->Commands
= newCommands
;
461 cp
->NumberOfCommands
= newNumberOfCommands
;
466 /*--------------------------------------------------------------------------*/
467 void kwsysProcess_SetTimeout(kwsysProcess
* cp
, double timeout
)
473 cp
->Timeout
= timeout
;
480 /*--------------------------------------------------------------------------*/
481 int kwsysProcess_SetWorkingDirectory(kwsysProcess
* cp
, const char* dir
)
487 if(cp
->WorkingDirectory
== dir
)
491 if(cp
->WorkingDirectory
&& dir
&& strcmp(cp
->WorkingDirectory
, dir
) == 0)
495 if(cp
->WorkingDirectory
)
497 free(cp
->WorkingDirectory
);
498 cp
->WorkingDirectory
= 0;
502 cp
->WorkingDirectory
= (char*)malloc(strlen(dir
) + 1);
503 if(!cp
->WorkingDirectory
)
507 strcpy(cp
->WorkingDirectory
, dir
);
512 /*--------------------------------------------------------------------------*/
513 int kwsysProcess_SetPipeFile(kwsysProcess
* cp
, int prPipe
, const char* file
)
522 case kwsysProcess_Pipe_STDIN
: pfile
= &cp
->PipeFileSTDIN
; break;
523 case kwsysProcess_Pipe_STDOUT
: pfile
= &cp
->PipeFileSTDOUT
; break;
524 case kwsysProcess_Pipe_STDERR
: pfile
= &cp
->PipeFileSTDERR
; break;
534 *pfile
= malloc(strlen(file
)+1);
539 strcpy(*pfile
, file
);
542 /* If we are redirecting the pipe, do not share it or use a native
546 kwsysProcess_SetPipeNative(cp
, prPipe
, 0);
547 kwsysProcess_SetPipeShared(cp
, prPipe
, 0);
552 /*--------------------------------------------------------------------------*/
553 void kwsysProcess_SetPipeShared(kwsysProcess
* cp
, int prPipe
, int shared
)
562 case kwsysProcess_Pipe_STDIN
: cp
->PipeSharedSTDIN
= shared
?1:0; break;
563 case kwsysProcess_Pipe_STDOUT
: cp
->PipeSharedSTDOUT
= shared
?1:0; break;
564 case kwsysProcess_Pipe_STDERR
: cp
->PipeSharedSTDERR
= shared
?1:0; break;
568 /* If we are sharing the pipe, do not redirect it to a file or use a
572 kwsysProcess_SetPipeFile(cp
, prPipe
, 0);
573 kwsysProcess_SetPipeNative(cp
, prPipe
, 0);
577 /*--------------------------------------------------------------------------*/
578 void kwsysProcess_SetPipeNative(kwsysProcess
* cp
, int prPipe
, int p
[2])
580 int* pPipeNative
= 0;
589 case kwsysProcess_Pipe_STDIN
: pPipeNative
= cp
->PipeNativeSTDIN
; break;
590 case kwsysProcess_Pipe_STDOUT
: pPipeNative
= cp
->PipeNativeSTDOUT
; break;
591 case kwsysProcess_Pipe_STDERR
: pPipeNative
= cp
->PipeNativeSTDERR
; break;
595 /* Copy the native pipe descriptors provided. */
598 pPipeNative
[0] = p
[0];
599 pPipeNative
[1] = p
[1];
607 /* If we are using a native pipe, do not share it or redirect it to
611 kwsysProcess_SetPipeFile(cp
, prPipe
, 0);
612 kwsysProcess_SetPipeShared(cp
, prPipe
, 0);
616 /*--------------------------------------------------------------------------*/
617 int kwsysProcess_GetOption(kwsysProcess
* cp
, int optionId
)
626 case kwsysProcess_Option_Detach
: return cp
->OptionDetach
;
627 case kwsysProcess_Option_Verbatim
: return cp
->Verbatim
;
632 /*--------------------------------------------------------------------------*/
633 void kwsysProcess_SetOption(kwsysProcess
* cp
, int optionId
, int value
)
642 case kwsysProcess_Option_Detach
: cp
->OptionDetach
= value
; break;
643 case kwsysProcess_Option_Verbatim
: cp
->Verbatim
= value
; break;
648 /*--------------------------------------------------------------------------*/
649 int kwsysProcess_GetState(kwsysProcess
* cp
)
651 return cp
? cp
->State
: kwsysProcess_State_Error
;
654 /*--------------------------------------------------------------------------*/
655 int kwsysProcess_GetExitException(kwsysProcess
* cp
)
657 return cp
? cp
->ExitException
: kwsysProcess_Exception_Other
;
660 /*--------------------------------------------------------------------------*/
661 int kwsysProcess_GetExitCode(kwsysProcess
* cp
)
663 return cp
? cp
->ExitCode
: 0;
666 /*--------------------------------------------------------------------------*/
667 int kwsysProcess_GetExitValue(kwsysProcess
* cp
)
669 return cp
? cp
->ExitValue
: -1;
672 /*--------------------------------------------------------------------------*/
673 const char* kwsysProcess_GetErrorString(kwsysProcess
* cp
)
677 return "Process management structure could not be allocated";
679 else if(cp
->State
== kwsysProcess_State_Error
)
681 return cp
->ErrorMessage
;
686 /*--------------------------------------------------------------------------*/
687 const char* kwsysProcess_GetExceptionString(kwsysProcess
* cp
)
691 return "GetExceptionString called with NULL process management structure";
693 else if(cp
->State
== kwsysProcess_State_Exception
)
695 return cp
->ExitExceptionString
;
697 return "No exception";
700 /*--------------------------------------------------------------------------*/
701 void kwsysProcess_Execute(kwsysProcess
* cp
)
704 kwsysProcessCreateInformation si
= {-1, -1, -1, {-1, -1}};
706 /* Do not execute a second copy simultaneously. */
707 if(!cp
|| cp
->State
== kwsysProcess_State_Executing
)
712 /* Initialize the control structure for a new process. */
713 if(!kwsysProcessInitialize(cp
))
715 strcpy(cp
->ErrorMessage
, "Out of memory");
716 cp
->State
= kwsysProcess_State_Error
;
720 /* Save the real working directory of this process and change to
721 the working directory for the child processes. This is needed
722 to make pipe file paths evaluate correctly. */
723 if(cp
->WorkingDirectory
)
726 if(!getcwd(cp
->RealWorkingDirectory
, cp
->RealWorkingDirectoryLength
))
728 kwsysProcessCleanup(cp
, 1);
732 /* Some platforms specify that the chdir call may be
733 interrupted. Repeat the call until it finishes. */
734 while(((r
= chdir(cp
->WorkingDirectory
)) < 0) && (errno
== EINTR
));
737 kwsysProcessCleanup(cp
, 1);
742 /* If not running a detached child, add this object to the global
743 set of process objects that wish to be notified when a child
745 if(!cp
->OptionDetach
)
747 if(!kwsysProcessesAdd(cp
))
749 kwsysProcessCleanup(cp
, 1);
754 /* Setup the stderr pipe to be shared by all processes. */
756 /* Create the pipe. */
760 kwsysProcessCleanup(cp
, 1);
764 /* Store the pipe. */
765 cp
->PipeReadEnds
[KWSYSPE_PIPE_STDERR
] = p
[0];
768 /* Set close-on-exec flag on the pipe's ends. */
769 if((fcntl(p
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
770 (fcntl(p
[1], F_SETFD
, FD_CLOEXEC
) < 0))
772 kwsysProcessCleanup(cp
, 1);
773 kwsysProcessCleanupDescriptor(&si
.StdErr
);
777 /* Set to non-blocking in case select lies, or for the polling
779 if(!kwsysProcessSetNonBlocking(p
[0]))
781 kwsysProcessCleanup(cp
, 1);
782 kwsysProcessCleanupDescriptor(&si
.StdErr
);
787 /* Replace the stderr pipe with a file if requested. In this case
788 the select call will report that stderr is closed immediately. */
789 if(cp
->PipeFileSTDERR
)
791 if(!kwsysProcessSetupOutputPipeFile(&si
.StdErr
, cp
->PipeFileSTDERR
))
793 kwsysProcessCleanup(cp
, 1);
794 kwsysProcessCleanupDescriptor(&si
.StdErr
);
799 /* Replace the stderr pipe with the parent's if requested. In this
800 case the select call will report that stderr is closed
802 if(cp
->PipeSharedSTDERR
)
804 kwsysProcessCleanupDescriptor(&si
.StdErr
);
808 /* Replace the stderr pipe with the native pipe provided if any. In
809 this case the select call will report that stderr is closed
811 if(cp
->PipeNativeSTDERR
[1] >= 0)
813 if(!kwsysProcessSetupOutputPipeNative(&si
.StdErr
, cp
->PipeNativeSTDERR
))
815 kwsysProcessCleanup(cp
, 1);
816 kwsysProcessCleanupDescriptor(&si
.StdErr
);
821 /* The timeout period starts now. */
822 cp
->StartTime
= kwsysProcessTimeGetCurrent();
823 cp
->TimeoutTime
.tv_sec
= -1;
824 cp
->TimeoutTime
.tv_usec
= -1;
826 /* Create the pipeline of processes. */
830 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
832 if(!kwsysProcessCreate(cp
, i
, &si
, &readEnd
))
837 /* Set the output pipe of the last process to be non-blocking in
838 case select lies, or for the polling implementation. */
839 if(i
== (cp
->NumberOfCommands
-1) && !kwsysProcessSetNonBlocking(readEnd
))
846 kwsysProcessCleanup(cp
, 1);
848 /* Release resources that may have been allocated for this
849 process before an error occurred. */
850 kwsysProcessCleanupDescriptor(&readEnd
);
853 kwsysProcessCleanupDescriptor(&si
.StdIn
);
857 kwsysProcessCleanupDescriptor(&si
.StdOut
);
861 kwsysProcessCleanupDescriptor(&si
.StdErr
);
863 kwsysProcessCleanupDescriptor(&si
.ErrorPipe
[0]);
864 kwsysProcessCleanupDescriptor(&si
.ErrorPipe
[1]);
868 /* Save a handle to the output pipe for the last process. */
869 cp
->PipeReadEnds
[KWSYSPE_PIPE_STDOUT
] = readEnd
;
872 /* The parent process does not need the output pipe write ends. */
875 kwsysProcessCleanupDescriptor(&si
.StdErr
);
878 /* Restore the working directory. */
879 if(cp
->RealWorkingDirectory
)
881 /* Some platforms specify that the chdir call may be
882 interrupted. Repeat the call until it finishes. */
883 while((chdir(cp
->RealWorkingDirectory
) < 0) && (errno
== EINTR
));
884 free(cp
->RealWorkingDirectory
);
885 cp
->RealWorkingDirectory
= 0;
888 /* All the pipes are now open. */
889 cp
->PipesLeft
= KWSYSPE_PIPE_COUNT
;
891 /* The process has now started. */
892 cp
->State
= kwsysProcess_State_Executing
;
893 cp
->Detached
= cp
->OptionDetach
;
896 /*--------------------------------------------------------------------------*/
897 kwsysEXPORT
void kwsysProcess_Disown(kwsysProcess
* cp
)
899 /* Make sure a detached child process is running. */
900 if(!cp
|| !cp
->Detached
|| cp
->State
!= kwsysProcess_State_Executing
||
901 cp
->TimeoutExpired
|| cp
->Killed
)
906 /* Close all the pipes safely. */
907 kwsysProcessClosePipes(cp
);
909 /* We will not wait for exit, so cleanup now. */
910 kwsysProcessCleanup(cp
, 0);
912 /* The process has been disowned. */
913 cp
->State
= kwsysProcess_State_Disowned
;
916 /*--------------------------------------------------------------------------*/
917 typedef struct kwsysProcessWaitData_s
923 kwsysProcessTime TimeoutTime
;
924 } kwsysProcessWaitData
;
925 static int kwsysProcessWaitForPipe(kwsysProcess
* cp
, char** data
, int* length
,
926 kwsysProcessWaitData
* wd
);
928 /*--------------------------------------------------------------------------*/
929 int kwsysProcess_WaitForData(kwsysProcess
* cp
, char** data
, int* length
,
932 kwsysProcessTime userStartTime
= {0, 0};
933 kwsysProcessWaitData wd
=
936 kwsysProcess_Pipe_None
,
941 wd
.UserTimeout
= userTimeout
;
942 /* Make sure we are executing a process. */
943 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
|| cp
->Killed
||
946 return kwsysProcess_Pipe_None
;
949 /* Record the time at which user timeout period starts. */
952 userStartTime
= kwsysProcessTimeGetCurrent();
955 /* Calculate the time at which a timeout will expire, and whether it
956 is the user or process timeout. */
957 wd
.User
= kwsysProcessGetTimeoutTime(cp
, userTimeout
,
960 /* Data can only be available when pipes are open. If the process
961 is not running, cp->PipesLeft will be 0. */
962 while(cp
->PipesLeft
> 0 &&
963 !kwsysProcessWaitForPipe(cp
, data
, length
, &wd
)) {}
965 /* Update the user timeout. */
968 kwsysProcessTime userEndTime
= kwsysProcessTimeGetCurrent();
969 kwsysProcessTime difference
= kwsysProcessTimeSubtract(userEndTime
,
971 double d
= kwsysProcessTimeToDouble(difference
);
979 /* Check what happened. */
982 /* Data are ready on a pipe. */
987 /* A timeout has expired. */
990 /* The user timeout has expired. It has no time left. */
991 return kwsysProcess_Pipe_Timeout
;
995 /* The process timeout has expired. Kill the children now. */
996 kwsysProcess_Kill(cp
);
998 cp
->TimeoutExpired
= 1;
999 return kwsysProcess_Pipe_None
;
1004 /* No pipes are left open. */
1005 return kwsysProcess_Pipe_None
;
1009 /*--------------------------------------------------------------------------*/
1010 static int kwsysProcessWaitForPipe(kwsysProcess
* cp
, char** data
, int* length
,
1011 kwsysProcessWaitData
* wd
)
1014 kwsysProcessTimeNative timeoutLength
;
1016 #if KWSYSPE_USE_SELECT
1019 kwsysProcessTimeNative
* timeout
= 0;
1021 /* Check for any open pipes with data reported ready by the last
1022 call to select. According to "man select_tut" we must deal
1023 with all descriptors reported by a call to select before
1024 passing them to another select call. */
1025 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1027 if(cp
->PipeReadEnds
[i
] >= 0 &&
1028 FD_ISSET(cp
->PipeReadEnds
[i
], &cp
->PipeSet
))
1030 kwsysProcess_ssize_t n
;
1032 /* We are handling this pipe now. Remove it from the set. */
1033 FD_CLR(cp
->PipeReadEnds
[i
], &cp
->PipeSet
);
1035 /* The pipe is ready to read without blocking. Keep trying to
1036 read until the operation is not interrupted. */
1037 while(((n
= read(cp
->PipeReadEnds
[i
], cp
->PipeBuffer
,
1038 KWSYSPE_PIPE_BUFFER_SIZE
)) < 0) && (errno
== EINTR
));
1041 /* We have data on this pipe. */
1042 if(i
== KWSYSPE_PIPE_SIGNAL
)
1044 /* A child process has terminated. */
1045 kwsysProcessDestroy(cp
);
1047 else if(data
&& length
)
1049 /* Report this data. */
1050 *data
= cp
->PipeBuffer
;
1054 case KWSYSPE_PIPE_STDOUT
:
1055 wd
->PipeId
= kwsysProcess_Pipe_STDOUT
; break;
1056 case KWSYSPE_PIPE_STDERR
:
1057 wd
->PipeId
= kwsysProcess_Pipe_STDERR
; break;
1062 else if(n
< 0 && errno
== EAGAIN
)
1064 /* No data are really ready. The select call lied. See the
1065 "man select" page on Linux for cases when this occurs. */
1069 /* We are done reading from this pipe. */
1070 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1076 /* If we have data, break early. */
1082 /* Make sure the set is empty (it should always be empty here
1084 FD_ZERO(&cp
->PipeSet
);
1086 /* Setup a timeout if required. */
1087 if(wd
->TimeoutTime
.tv_sec
< 0)
1093 timeout
= &timeoutLength
;
1095 if(kwsysProcessGetTimeoutLeft(&wd
->TimeoutTime
,
1096 wd
->User
?wd
->UserTimeout
:0,
1099 /* Timeout has already expired. */
1104 /* Add the pipe reading ends that are still open. */
1106 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1108 if(cp
->PipeReadEnds
[i
] >= 0)
1110 FD_SET(cp
->PipeReadEnds
[i
], &cp
->PipeSet
);
1111 if(cp
->PipeReadEnds
[i
] > max
)
1113 max
= cp
->PipeReadEnds
[i
];
1118 /* Make sure we have a non-empty set. */
1121 /* All pipes have closed. Child has terminated. */
1125 /* Run select to block until data are available. Repeat call
1126 until it is not interrupted. */
1127 while(((numReady
= select(max
+1, &cp
->PipeSet
, 0, 0, timeout
)) < 0) &&
1130 /* Check result of select. */
1133 /* Select's timeout expired. */
1137 else if(numReady
< 0)
1139 /* Select returned an error. Leave the error description in the
1141 strncpy(cp
->ErrorMessage
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
1143 /* Kill the children now. */
1144 kwsysProcess_Kill(cp
);
1146 cp
->SelectError
= 1;
1151 /* Poll pipes for data since we do not have select. */
1152 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1154 if(cp
->PipeReadEnds
[i
] >= 0)
1156 const int fd
= cp
->PipeReadEnds
[i
];
1157 int n
= read(fd
, cp
->PipeBuffer
, KWSYSPE_PIPE_BUFFER_SIZE
);
1160 /* We have data on this pipe. */
1161 if(i
== KWSYSPE_PIPE_SIGNAL
)
1163 /* A child process has terminated. */
1164 kwsysProcessDestroy(cp
);
1166 else if(data
&& length
)
1168 /* Report this data. */
1169 *data
= cp
->PipeBuffer
;
1173 case KWSYSPE_PIPE_STDOUT
:
1174 wd
->PipeId
= kwsysProcess_Pipe_STDOUT
; break;
1175 case KWSYSPE_PIPE_STDERR
:
1176 wd
->PipeId
= kwsysProcess_Pipe_STDERR
; break;
1181 else if (n
== 0) /* EOF */
1183 /* We are done reading from this pipe. */
1184 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1187 else if (n
< 0) /* error */
1189 if((errno
!= EINTR
) && (errno
!= EAGAIN
))
1191 strncpy(cp
->ErrorMessage
,strerror(errno
),
1192 KWSYSPE_PIPE_BUFFER_SIZE
);
1193 /* Kill the children now. */
1194 kwsysProcess_Kill(cp
);
1196 cp
->SelectError
= 1;
1203 /* If we have data, break early. */
1209 if(kwsysProcessGetTimeoutLeft(&wd
->TimeoutTime
, wd
->User
?wd
->UserTimeout
:0,
1212 /* Timeout has already expired. */
1217 if((timeoutLength
.tv_sec
== 0) && (timeoutLength
.tv_usec
== 0))
1219 /* Timeout has already expired. */
1224 /* Sleep a little, try again. */
1226 unsigned int msec
= ((timeoutLength
.tv_sec
* 1000) +
1227 (timeoutLength
.tv_usec
/ 1000));
1230 msec
= 100000; /* do not sleep more than 100 milliseconds at a time */
1232 kwsysProcess_usleep(msec
);
1238 /*--------------------------------------------------------------------------*/
1239 int kwsysProcess_WaitForExit(kwsysProcess
* cp
, double* userTimeout
)
1244 /* Make sure we are executing a process. */
1245 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
)
1250 /* Wait for all the pipes to close. Ignore all data. */
1251 while((prPipe
= kwsysProcess_WaitForData(cp
, 0, 0, userTimeout
)) > 0)
1253 if(prPipe
== kwsysProcess_Pipe_Timeout
)
1259 /* Check if there was an error in one of the waitpid calls. */
1260 if(cp
->State
== kwsysProcess_State_Error
)
1262 /* The error message is already in its buffer. Tell
1263 kwsysProcessCleanup to not create it. */
1264 kwsysProcessCleanup(cp
, 0);
1268 /* Check whether the child reported an error invoking the process. */
1271 /* The error message is already in its buffer. Tell
1272 kwsysProcessCleanup to not create it. */
1273 kwsysProcessCleanup(cp
, 0);
1274 cp
->State
= kwsysProcess_State_Error
;
1278 /* Use the status of the last process in the pipeline. */
1279 status
= cp
->CommandExitCodes
[cp
->NumberOfCommands
-1];
1281 /* Determine the outcome. */
1284 /* We killed the child. */
1285 cp
->State
= kwsysProcess_State_Killed
;
1287 else if(cp
->TimeoutExpired
)
1289 /* The timeout expired. */
1290 cp
->State
= kwsysProcess_State_Expired
;
1292 else if(WIFEXITED(status
))
1294 /* The child exited normally. */
1295 cp
->State
= kwsysProcess_State_Exited
;
1296 cp
->ExitException
= kwsysProcess_Exception_None
;
1297 cp
->ExitCode
= status
;
1298 cp
->ExitValue
= (int)WEXITSTATUS(status
);
1300 else if(WIFSIGNALED(status
))
1302 /* The child received an unhandled signal. */
1303 cp
->State
= kwsysProcess_State_Exception
;
1304 cp
->ExitCode
= status
;
1305 kwsysProcessSetExitException(cp
, (int)WTERMSIG(status
));
1309 /* Error getting the child return code. */
1310 strcpy(cp
->ErrorMessage
, "Error getting child return code.");
1311 cp
->State
= kwsysProcess_State_Error
;
1314 /* Normal cleanup. */
1315 kwsysProcessCleanup(cp
, 0);
1319 /*--------------------------------------------------------------------------*/
1320 void kwsysProcess_Kill(kwsysProcess
* cp
)
1324 /* Make sure we are executing a process. */
1325 if(!cp
|| cp
->State
!= kwsysProcess_State_Executing
)
1330 /* First close the child exit report pipe write end to avoid causing a
1331 SIGPIPE when the child terminates and our signal handler tries to
1332 report it after we have already closed the read end. */
1333 kwsysProcessCleanupDescriptor(&cp
->SignalPipe
);
1335 #if !defined(__APPLE__)
1336 /* Close all the pipe read ends. Do this before killing the
1337 children because Cygwin has problems killing processes that are
1338 blocking to wait for writing to their output pipes. */
1339 kwsysProcessClosePipes(cp
);
1342 /* Kill the children. */
1344 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1349 /* Kill the child. */
1350 kwsysProcessKill(cp
->ForkPIDs
[i
]);
1352 /* Reap the child. Keep trying until the call is not
1354 while((waitpid(cp
->ForkPIDs
[i
], &status
, 0) < 0) && (errno
== EINTR
));
1358 #if defined(__APPLE__)
1359 /* Close all the pipe read ends. Do this after killing the
1360 children because OS X has problems closing pipe read ends whose
1361 pipes are full and still have an open write end. */
1362 kwsysProcessClosePipes(cp
);
1365 cp
->CommandsLeft
= 0;
1368 /*--------------------------------------------------------------------------*/
1369 /* Initialize a process control structure for kwsysProcess_Execute. */
1370 static int kwsysProcessInitialize(kwsysProcess
* cp
)
1373 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1375 cp
->PipeReadEnds
[i
] = -1;
1377 cp
->SignalPipe
= -1;
1378 cp
->SelectError
= 0;
1379 cp
->StartTime
.tv_sec
= -1;
1380 cp
->StartTime
.tv_usec
= -1;
1381 cp
->TimeoutTime
.tv_sec
= -1;
1382 cp
->TimeoutTime
.tv_usec
= -1;
1383 cp
->TimeoutExpired
= 0;
1385 cp
->CommandsLeft
= 0;
1386 #if KWSYSPE_USE_SELECT
1387 FD_ZERO(&cp
->PipeSet
);
1389 cp
->State
= kwsysProcess_State_Starting
;
1391 cp
->ExitException
= kwsysProcess_Exception_None
;
1394 cp
->ErrorMessage
[0] = 0;
1395 strcpy(cp
->ExitExceptionString
, "No exception");
1401 cp
->ForkPIDs
= (pid_t
*)malloc(sizeof(pid_t
)*cp
->NumberOfCommands
);
1406 memset(cp
->ForkPIDs
, 0, sizeof(pid_t
)*cp
->NumberOfCommands
);
1408 if(cp
->CommandExitCodes
)
1410 free(cp
->CommandExitCodes
);
1412 cp
->CommandExitCodes
= (int*)malloc(sizeof(int)*cp
->NumberOfCommands
);
1413 if(!cp
->CommandExitCodes
)
1417 memset(cp
->CommandExitCodes
, 0, sizeof(int)*cp
->NumberOfCommands
);
1419 /* Allocate memory to save the real working directory. */
1420 if ( cp
->WorkingDirectory
)
1422 #if defined(MAXPATHLEN)
1423 cp
->RealWorkingDirectoryLength
= MAXPATHLEN
;
1424 #elif defined(PATH_MAX)
1425 cp
->RealWorkingDirectoryLength
= PATH_MAX
;
1427 cp
->RealWorkingDirectoryLength
= 4096;
1429 cp
->RealWorkingDirectory
= malloc(cp
->RealWorkingDirectoryLength
);
1430 if(!cp
->RealWorkingDirectory
)
1439 /*--------------------------------------------------------------------------*/
1440 /* Free all resources used by the given kwsysProcess instance that were
1441 allocated by kwsysProcess_Execute. */
1442 static void kwsysProcessCleanup(kwsysProcess
* cp
, int error
)
1448 /* We are cleaning up due to an error. Report the error message
1449 if one has not been provided already. */
1450 if(cp
->ErrorMessage
[0] == 0)
1452 strncpy(cp
->ErrorMessage
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
1455 /* Set the error state. */
1456 cp
->State
= kwsysProcess_State_Error
;
1458 /* Kill any children already started. */
1462 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1466 /* Kill the child. */
1467 kwsysProcessKill(cp
->ForkPIDs
[i
]);
1469 /* Reap the child. Keep trying until the call is not
1471 while((waitpid(cp
->ForkPIDs
[i
], &status
, 0) < 0) &&
1477 /* Restore the working directory. */
1478 if(cp
->RealWorkingDirectory
)
1480 while((chdir(cp
->RealWorkingDirectory
) < 0) && (errno
== EINTR
));
1484 /* If not creating a detached child, remove this object from the
1485 global set of process objects that wish to be notified when a
1487 if(!cp
->OptionDetach
)
1489 kwsysProcessesRemove(cp
);
1498 if(cp
->RealWorkingDirectory
)
1500 free(cp
->RealWorkingDirectory
);
1501 cp
->RealWorkingDirectory
= 0;
1504 /* Close pipe handles. */
1505 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1507 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1511 /*--------------------------------------------------------------------------*/
1512 /* Close the given file descriptor if it is open. Reset its value to -1. */
1513 static void kwsysProcessCleanupDescriptor(int* pfd
)
1515 if(pfd
&& *pfd
>= 0)
1517 /* Keep trying to close until it is not interrupted by a
1519 while((close(*pfd
) < 0) && (errno
== EINTR
));
1524 /*--------------------------------------------------------------------------*/
1525 static void kwsysProcessClosePipes(kwsysProcess
* cp
)
1529 /* Close any pipes that are still open. */
1530 for(i
=0; i
< KWSYSPE_PIPE_COUNT
; ++i
)
1532 if(cp
->PipeReadEnds
[i
] >= 0)
1534 #if KWSYSPE_USE_SELECT
1535 /* If the pipe was reported by the last call to select, we must
1536 read from it. This is needed to satisfy the suggestions from
1537 "man select_tut" and is not needed for the polling
1538 implementation. Ignore the data. */
1539 if(FD_ISSET(cp
->PipeReadEnds
[i
], &cp
->PipeSet
))
1541 /* We are handling this pipe now. Remove it from the set. */
1542 FD_CLR(cp
->PipeReadEnds
[i
], &cp
->PipeSet
);
1544 /* The pipe is ready to read without blocking. Keep trying to
1545 read until the operation is not interrupted. */
1546 while((read(cp
->PipeReadEnds
[i
], cp
->PipeBuffer
,
1547 KWSYSPE_PIPE_BUFFER_SIZE
) < 0) && (errno
== EINTR
));
1551 /* We are done reading from this pipe. */
1552 kwsysProcessCleanupDescriptor(&cp
->PipeReadEnds
[i
]);
1558 /*--------------------------------------------------------------------------*/
1559 static int kwsysProcessSetNonBlocking(int fd
)
1561 int flags
= fcntl(fd
, F_GETFL
);
1564 flags
= fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
);
1569 /*--------------------------------------------------------------------------*/
1570 static int kwsysProcessCreate(kwsysProcess
* cp
, int prIndex
,
1571 kwsysProcessCreateInformation
* si
, int* readEnd
)
1573 /* Setup the process's stdin. */
1576 si
->StdIn
= *readEnd
;
1579 else if(cp
->PipeFileSTDIN
)
1581 /* Open a file for the child's stdin to read. */
1582 si
->StdIn
= open(cp
->PipeFileSTDIN
, O_RDONLY
);
1588 /* Set close-on-exec flag on the pipe's end. */
1589 if(fcntl(si
->StdIn
, F_SETFD
, FD_CLOEXEC
) < 0)
1594 else if(cp
->PipeSharedSTDIN
)
1598 else if(cp
->PipeNativeSTDIN
[0] >= 0)
1600 si
->StdIn
= cp
->PipeNativeSTDIN
[0];
1602 /* Set close-on-exec flag on the pipe's ends. The read end will
1603 be dup2-ed into the stdin descriptor after the fork but before
1605 if((fcntl(cp
->PipeNativeSTDIN
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1606 (fcntl(cp
->PipeNativeSTDIN
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1616 /* Setup the process's stdout. */
1618 /* Create the pipe. */
1627 /* Set close-on-exec flag on the pipe's ends. */
1628 if((fcntl(p
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1629 (fcntl(p
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1635 /* Replace the stdout pipe with a file if requested. In this case
1636 the select call will report that stdout is closed immediately. */
1637 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeFileSTDOUT
)
1639 if(!kwsysProcessSetupOutputPipeFile(&si
->StdOut
, cp
->PipeFileSTDOUT
))
1645 /* Replace the stdout pipe with the parent's if requested. In this
1646 case the select call will report that stderr is closed
1648 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeSharedSTDOUT
)
1650 kwsysProcessCleanupDescriptor(&si
->StdOut
);
1654 /* Replace the stdout pipe with the native pipe provided if any. In
1655 this case the select call will report that stdout is closed
1657 if(prIndex
== cp
->NumberOfCommands
-1 && cp
->PipeNativeSTDOUT
[1] >= 0)
1659 if(!kwsysProcessSetupOutputPipeNative(&si
->StdOut
, cp
->PipeNativeSTDOUT
))
1665 /* Create the error reporting pipe. */
1666 if(pipe(si
->ErrorPipe
) < 0)
1671 /* Set close-on-exec flag on the error pipe's write end. */
1672 if(fcntl(si
->ErrorPipe
[1], F_SETFD
, FD_CLOEXEC
) < 0)
1677 /* Fork off a child process. */
1678 cp
->ForkPIDs
[prIndex
] = kwsysProcessFork(cp
, si
);
1679 if(cp
->ForkPIDs
[prIndex
] < 0)
1684 if(cp
->ForkPIDs
[prIndex
] == 0)
1686 /* Close the read end of the error reporting pipe. */
1687 close(si
->ErrorPipe
[0]);
1689 /* Setup the stdin, stdout, and stderr pipes. */
1694 else if(si
->StdIn
< 0)
1700 dup2(si
->StdOut
, 1);
1704 dup2(si
->StdErr
, 2);
1707 /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1708 All other pipe handles will be closed when exec succeeds. */
1709 fcntl(0, F_SETFD
, 0);
1710 fcntl(1, F_SETFD
, 0);
1711 fcntl(2, F_SETFD
, 0);
1713 /* Restore all default signal handlers. */
1714 kwsysProcessRestoreDefaultSignalHandlers();
1716 /* Execute the real process. If successful, this does not return. */
1717 execvp(cp
->Commands
[prIndex
][0], cp
->Commands
[prIndex
]);
1719 /* Failure. Report error to parent and terminate. */
1720 kwsysProcessChildErrorExit(si
->ErrorPipe
[1]);
1723 /* A child has been created. */
1726 /* We are done with the error reporting pipe write end. */
1727 kwsysProcessCleanupDescriptor(&si
->ErrorPipe
[1]);
1729 /* Block until the child's exec call succeeds and closes the error
1730 pipe or writes data to the pipe to report an error. */
1732 kwsysProcess_ssize_t total
= 0;
1733 kwsysProcess_ssize_t n
= 1;
1734 /* Read the entire error message up to the length of our buffer. */
1735 while(total
< KWSYSPE_PIPE_BUFFER_SIZE
&& n
> 0)
1737 /* Keep trying to read until the operation is not interrupted. */
1738 while(((n
= read(si
->ErrorPipe
[0], cp
->ErrorMessage
+total
,
1739 KWSYSPE_PIPE_BUFFER_SIZE
-total
)) < 0) &&
1747 /* We are done with the error reporting pipe read end. */
1748 kwsysProcessCleanupDescriptor(&si
->ErrorPipe
[0]);
1752 /* The child failed to execute the process. */
1757 /* Successfully created this child process. */
1758 if(prIndex
> 0 || si
->StdIn
> 0)
1760 /* The parent process does not need the input pipe read end. */
1761 kwsysProcessCleanupDescriptor(&si
->StdIn
);
1764 /* The parent process does not need the output pipe write ends. */
1767 kwsysProcessCleanupDescriptor(&si
->StdOut
);
1773 /*--------------------------------------------------------------------------*/
1774 static void kwsysProcessDestroy(kwsysProcess
* cp
)
1776 /* A child process has terminated. Reap it if it is one handled by
1779 for(i
=0; i
< cp
->NumberOfCommands
; ++i
)
1784 while(((result
= waitpid(cp
->ForkPIDs
[i
],
1785 &cp
->CommandExitCodes
[i
], WNOHANG
)) < 0) &&
1789 /* This child has termianted. */
1790 cp
->ForkPIDs
[i
] = 0;
1791 if(--cp
->CommandsLeft
== 0)
1793 /* All children have terminated. Close the signal pipe
1794 write end so that no more notifications are sent to this
1796 kwsysProcessCleanupDescriptor(&cp
->SignalPipe
);
1798 /* TODO: Once the children have terminated, switch
1799 WaitForData to use a non-blocking read to get the
1800 rest of the data from the pipe. This is needed when
1801 grandchildren keep the output pipes open. */
1804 else if(result
< 0 && cp
->State
!= kwsysProcess_State_Error
)
1806 /* Unexpected error. Report the first time this happens. */
1807 strncpy(cp
->ErrorMessage
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
1808 cp
->State
= kwsysProcess_State_Error
;
1814 /*--------------------------------------------------------------------------*/
1815 static int kwsysProcessSetupOutputPipeFile(int* p
, const char* name
)
1823 /* Close the existing descriptor. */
1824 kwsysProcessCleanupDescriptor(p
);
1826 /* Open a file for the pipe to write (permissions 644). */
1827 if((fout
= open(name
, O_WRONLY
| O_CREAT
| O_TRUNC
,
1828 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
)) < 0)
1833 /* Set close-on-exec flag on the pipe's end. */
1834 if(fcntl(fout
, F_SETFD
, FD_CLOEXEC
) < 0)
1839 /* Assign the replacement descriptor. */
1844 /*--------------------------------------------------------------------------*/
1845 static int kwsysProcessSetupOutputPipeNative(int* p
, int des
[2])
1847 /* Close the existing descriptor. */
1848 kwsysProcessCleanupDescriptor(p
);
1850 /* Set close-on-exec flag on the pipe's ends. The proper end will
1851 be dup2-ed into the standard descriptor number after fork but
1853 if((fcntl(des
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
1854 (fcntl(des
[1], F_SETFD
, FD_CLOEXEC
) < 0))
1859 /* Assign the replacement descriptor. */
1864 /*--------------------------------------------------------------------------*/
1865 /* Get the time at which either the process or user timeout will
1866 expire. Returns 1 if the user timeout is first, and 0 otherwise. */
1867 static int kwsysProcessGetTimeoutTime(kwsysProcess
* cp
, double* userTimeout
,
1868 kwsysProcessTime
* timeoutTime
)
1870 /* The first time this is called, we need to calculate the time at
1871 which the child will timeout. */
1872 if(cp
->Timeout
&& cp
->TimeoutTime
.tv_sec
< 0)
1874 kwsysProcessTime length
= kwsysProcessTimeFromDouble(cp
->Timeout
);
1875 cp
->TimeoutTime
= kwsysProcessTimeAdd(cp
->StartTime
, length
);
1878 /* Start with process timeout. */
1879 *timeoutTime
= cp
->TimeoutTime
;
1881 /* Check if the user timeout is earlier. */
1884 kwsysProcessTime currentTime
= kwsysProcessTimeGetCurrent();
1885 kwsysProcessTime userTimeoutLength
= kwsysProcessTimeFromDouble(*userTimeout
);
1886 kwsysProcessTime userTimeoutTime
= kwsysProcessTimeAdd(currentTime
,
1888 if(timeoutTime
->tv_sec
< 0 ||
1889 kwsysProcessTimeLess(userTimeoutTime
, *timeoutTime
))
1891 *timeoutTime
= userTimeoutTime
;
1898 /*--------------------------------------------------------------------------*/
1899 /* Get the length of time before the given timeout time arrives.
1900 Returns 1 if the time has already arrived, and 0 otherwise. */
1901 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime
* timeoutTime
,
1902 double* userTimeout
,
1903 kwsysProcessTimeNative
* timeoutLength
)
1905 if(timeoutTime
->tv_sec
< 0)
1907 /* No timeout time has been requested. */
1912 /* Calculate the remaining time. */
1913 kwsysProcessTime currentTime
= kwsysProcessTimeGetCurrent();
1914 kwsysProcessTime timeLeft
= kwsysProcessTimeSubtract(*timeoutTime
,
1916 if(timeLeft
.tv_sec
< 0 && userTimeout
&& *userTimeout
<= 0)
1918 /* Caller has explicitly requested a zero timeout. */
1919 timeLeft
.tv_sec
= 0;
1920 timeLeft
.tv_usec
= 0;
1923 if(timeLeft
.tv_sec
< 0)
1925 /* Timeout has already expired. */
1930 /* There is some time left. */
1931 timeoutLength
->tv_sec
= timeLeft
.tv_sec
;
1932 timeoutLength
->tv_usec
= timeLeft
.tv_usec
;
1938 /*--------------------------------------------------------------------------*/
1939 static kwsysProcessTime
kwsysProcessTimeGetCurrent(void)
1941 kwsysProcessTime current
;
1942 kwsysProcessTimeNative current_native
;
1943 gettimeofday(¤t_native
, 0);
1944 current
.tv_sec
= (long)current_native
.tv_sec
;
1945 current
.tv_usec
= (long)current_native
.tv_usec
;
1949 /*--------------------------------------------------------------------------*/
1950 static double kwsysProcessTimeToDouble(kwsysProcessTime t
)
1952 return (double)t
.tv_sec
+ t
.tv_usec
*0.000001;
1955 /*--------------------------------------------------------------------------*/
1956 static kwsysProcessTime
kwsysProcessTimeFromDouble(double d
)
1960 t
.tv_usec
= (long)((d
-t
.tv_sec
)*1000000);
1964 /*--------------------------------------------------------------------------*/
1965 static int kwsysProcessTimeLess(kwsysProcessTime in1
, kwsysProcessTime in2
)
1967 return ((in1
.tv_sec
< in2
.tv_sec
) ||
1968 ((in1
.tv_sec
== in2
.tv_sec
) && (in1
.tv_usec
< in2
.tv_usec
)));
1971 /*--------------------------------------------------------------------------*/
1972 static kwsysProcessTime
kwsysProcessTimeAdd(kwsysProcessTime in1
, kwsysProcessTime in2
)
1974 kwsysProcessTime out
;
1975 out
.tv_sec
= in1
.tv_sec
+ in2
.tv_sec
;
1976 out
.tv_usec
= in1
.tv_usec
+ in2
.tv_usec
;
1977 if(out
.tv_usec
> 1000000)
1979 out
.tv_usec
-= 1000000;
1985 /*--------------------------------------------------------------------------*/
1986 static kwsysProcessTime
kwsysProcessTimeSubtract(kwsysProcessTime in1
, kwsysProcessTime in2
)
1988 kwsysProcessTime out
;
1989 out
.tv_sec
= in1
.tv_sec
- in2
.tv_sec
;
1990 out
.tv_usec
= in1
.tv_usec
- in2
.tv_usec
;
1993 out
.tv_usec
+= 1000000;
1999 /*--------------------------------------------------------------------------*/
2000 #define KWSYSPE_CASE(type, str) \
2001 cp->ExitException = kwsysProcess_Exception_##type; \
2002 strcpy(cp->ExitExceptionString, str)
2003 static void kwsysProcessSetExitException(kwsysProcess
* cp
, int sig
)
2008 case SIGSEGV
: KWSYSPE_CASE(Fault
, "Segmentation fault"); break;
2011 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2012 case SIGBUS
: KWSYSPE_CASE(Fault
, "Bus error"); break;
2016 case SIGFPE
: KWSYSPE_CASE(Numerical
, "Floating-point exception"); break;
2019 case SIGILL
: KWSYSPE_CASE(Illegal
, "Illegal instruction"); break;
2022 case SIGINT
: KWSYSPE_CASE(Interrupt
, "User interrupt"); break;
2025 case SIGABRT
: KWSYSPE_CASE(Other
, "Child aborted"); break;
2028 case SIGKILL
: KWSYSPE_CASE(Other
, "Child killed"); break;
2031 case SIGTERM
: KWSYSPE_CASE(Other
, "Child terminated"); break;
2034 case SIGHUP
: KWSYSPE_CASE(Other
, "SIGHUP"); break;
2037 case SIGQUIT
: KWSYSPE_CASE(Other
, "SIGQUIT"); break;
2040 case SIGTRAP
: KWSYSPE_CASE(Other
, "SIGTRAP"); break;
2043 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2044 case SIGIOT
: KWSYSPE_CASE(Other
, "SIGIOT"); break;
2048 case SIGUSR1
: KWSYSPE_CASE(Other
, "SIGUSR1"); break;
2051 case SIGUSR2
: KWSYSPE_CASE(Other
, "SIGUSR2"); break;
2054 case SIGPIPE
: KWSYSPE_CASE(Other
, "SIGPIPE"); break;
2057 case SIGALRM
: KWSYSPE_CASE(Other
, "SIGALRM"); break;
2060 case SIGSTKFLT
: KWSYSPE_CASE(Other
, "SIGSTKFLT"); break;
2063 case SIGCHLD
: KWSYSPE_CASE(Other
, "SIGCHLD"); break;
2064 #elif defined(SIGCLD)
2065 case SIGCLD
: KWSYSPE_CASE(Other
, "SIGCLD"); break;
2068 case SIGCONT
: KWSYSPE_CASE(Other
, "SIGCONT"); break;
2071 case SIGSTOP
: KWSYSPE_CASE(Other
, "SIGSTOP"); break;
2074 case SIGTSTP
: KWSYSPE_CASE(Other
, "SIGTSTP"); break;
2077 case SIGTTIN
: KWSYSPE_CASE(Other
, "SIGTTIN"); break;
2080 case SIGTTOU
: KWSYSPE_CASE(Other
, "SIGTTOU"); break;
2083 case SIGURG
: KWSYSPE_CASE(Other
, "SIGURG"); break;
2086 case SIGXCPU
: KWSYSPE_CASE(Other
, "SIGXCPU"); break;
2089 case SIGXFSZ
: KWSYSPE_CASE(Other
, "SIGXFSZ"); break;
2092 case SIGVTALRM
: KWSYSPE_CASE(Other
, "SIGVTALRM"); break;
2095 case SIGPROF
: KWSYSPE_CASE(Other
, "SIGPROF"); break;
2098 case SIGWINCH
: KWSYSPE_CASE(Other
, "SIGWINCH"); break;
2101 case SIGPOLL
: KWSYSPE_CASE(Other
, "SIGPOLL"); break;
2104 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2105 case SIGIO
: KWSYSPE_CASE(Other
, "SIGIO"); break;
2109 case SIGPWR
: KWSYSPE_CASE(Other
, "SIGPWR"); break;
2112 case SIGSYS
: KWSYSPE_CASE(Other
, "SIGSYS"); break;
2115 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2116 case SIGUNUSED
: KWSYSPE_CASE(Other
, "SIGUNUSED"); break;
2120 cp
->ExitException
= kwsysProcess_Exception_Other
;
2121 sprintf(cp
->ExitExceptionString
, "Signal %d", sig
);
2127 /*--------------------------------------------------------------------------*/
2128 /* When the child process encounters an error before its program is
2129 invoked, this is called to report the error to the parent and
2131 static void kwsysProcessChildErrorExit(int errorPipe
)
2133 /* Construct the error message. */
2134 char buffer
[KWSYSPE_PIPE_BUFFER_SIZE
];
2135 strncpy(buffer
, strerror(errno
), KWSYSPE_PIPE_BUFFER_SIZE
);
2137 /* Report the error to the parent through the special pipe. */
2138 write(errorPipe
, buffer
, strlen(buffer
));
2140 /* Terminate without cleanup. */
2144 /*--------------------------------------------------------------------------*/
2145 /* Restores all signal handlers to their default values. */
2146 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2148 struct sigaction act
;
2149 memset(&act
, 0, sizeof(struct sigaction
));
2150 act
.sa_handler
= SIG_DFL
;
2152 sigaction(SIGHUP
, &act
, 0);
2155 sigaction(SIGINT
, &act
, 0);
2158 sigaction(SIGQUIT
, &act
, 0);
2161 sigaction(SIGILL
, &act
, 0);
2164 sigaction(SIGTRAP
, &act
, 0);
2167 sigaction(SIGABRT
, &act
, 0);
2170 sigaction(SIGIOT
, &act
, 0);
2173 sigaction(SIGBUS
, &act
, 0);
2176 sigaction(SIGFPE
, &act
, 0);
2179 sigaction(SIGUSR1
, &act
, 0);
2182 sigaction(SIGSEGV
, &act
, 0);
2185 sigaction(SIGUSR2
, &act
, 0);
2188 sigaction(SIGPIPE
, &act
, 0);
2191 sigaction(SIGALRM
, &act
, 0);
2194 sigaction(SIGTERM
, &act
, 0);
2197 sigaction(SIGSTKFLT
, &act
, 0);
2200 sigaction(SIGCLD
, &act
, 0);
2203 sigaction(SIGCHLD
, &act
, 0);
2206 sigaction(SIGCONT
, &act
, 0);
2209 sigaction(SIGTSTP
, &act
, 0);
2212 sigaction(SIGTTIN
, &act
, 0);
2215 sigaction(SIGTTOU
, &act
, 0);
2218 sigaction(SIGURG
, &act
, 0);
2221 sigaction(SIGXCPU
, &act
, 0);
2224 sigaction(SIGXFSZ
, &act
, 0);
2227 sigaction(SIGVTALRM
, &act
, 0);
2230 sigaction(SIGPROF
, &act
, 0);
2233 sigaction(SIGWINCH
, &act
, 0);
2236 sigaction(SIGPOLL
, &act
, 0);
2239 sigaction(SIGIO
, &act
, 0);
2242 sigaction(SIGPWR
, &act
, 0);
2245 sigaction(SIGSYS
, &act
, 0);
2248 sigaction(SIGUNUSED
, &act
, 0);
2252 /*--------------------------------------------------------------------------*/
2253 static void kwsysProcessExit(void)
2258 /*--------------------------------------------------------------------------*/
2259 static pid_t
kwsysProcessFork(kwsysProcess
* cp
,
2260 kwsysProcessCreateInformation
* si
)
2262 /* Create a detached process if requested. */
2263 if(cp
->OptionDetach
)
2265 /* Create an intermediate process. */
2266 pid_t middle_pid
= fork();
2269 /* Fork failed. Return as if we were not detaching. */
2272 else if(middle_pid
== 0)
2274 /* This is the intermediate process. Create the real child. */
2275 pid_t child_pid
= fork();
2278 /* This is the real child process. There is nothing to do here. */
2283 /* Use the error pipe to report the pid to the real parent. */
2284 while((write(si
->ErrorPipe
[1], &child_pid
, sizeof(child_pid
)) < 0) &&
2287 /* Exit without cleanup. The parent holds all resources. */
2289 return 0; /* Never reached, but avoids SunCC warning. */
2294 /* This is the original parent process. The intermediate
2295 process will use the error pipe to report the pid of the
2299 while((read(si
->ErrorPipe
[0], &child_pid
, sizeof(child_pid
)) < 0) &&
2302 /* Wait for the intermediate process to exit and clean it up. */
2303 while((waitpid(middle_pid
, &status
, 0) < 0) && (errno
== EINTR
));
2309 /* Not creating a detached process. Use normal fork. */
2314 /*--------------------------------------------------------------------------*/
2315 /* We try to obtain process information by invoking the ps command.
2316 Here we define the command to call on each platform and the
2317 corresponding parsing format string. The parsing format should
2318 have two integers to store: the pid and then the ppid. */
2319 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
2320 # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2321 # define KWSYSPE_PS_FORMAT "%d %d\n"
2322 #elif defined(__hpux) || defined(__sparc) || defined(__sgi) || defined(_AIX)
2323 # define KWSYSPE_PS_COMMAND "ps -ef"
2324 # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
2325 #elif defined(__CYGWIN__)
2326 # define KWSYSPE_PS_COMMAND "ps aux"
2327 # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
2330 /*--------------------------------------------------------------------------*/
2331 static void kwsysProcessKill(pid_t process_id
)
2333 #if defined(__linux__) || defined(__CYGWIN__)
2337 /* Kill the process now to make sure it does not create more
2338 children. Do not reap it yet so we can identify its existing
2339 children. There is a small race condition here. If the child
2340 forks after we begin looking for children below but before it
2341 receives this kill signal we might miss a child. Also we might
2342 not be able to catch up to a fork bomb. */
2343 kill(process_id
, SIGKILL
);
2345 /* Kill all children if we can find them. */
2346 #if defined(__linux__) || defined(__CYGWIN__)
2347 /* First try using the /proc filesystem. */
2348 if((procdir
= opendir("/proc")) != NULL
)
2350 #if defined(MAXPATHLEN)
2351 char fname
[MAXPATHLEN
];
2352 #elif defined(PATH_MAX)
2353 char fname
[PATH_MAX
];
2357 char buffer
[KWSYSPE_PIPE_BUFFER_SIZE
+1];
2360 /* Each process has a directory in /proc whose name is the pid.
2361 Within this directory is a file called stat that has the
2364 pid (command line) status ppid ...
2366 We want to get the ppid for all processes. Those that have
2367 process_id as their parent should be recursively killed. */
2368 for(d
= readdir(procdir
); d
; d
= readdir(procdir
))
2371 if(sscanf(d
->d_name
, "%d", &pid
) == 1 && pid
!= 0)
2374 sprintf(fname
, "/proc/%d/stat", pid
);
2375 if(stat(fname
, &finfo
) == 0)
2377 FILE* f
= fopen(fname
, "r");
2380 int nread
= fread(buffer
, 1, KWSYSPE_PIPE_BUFFER_SIZE
, f
);
2381 buffer
[nread
] = '\0';
2384 const char* rparen
= strrchr(buffer
, ')');
2386 if(rparen
&& (sscanf(rparen
+1, "%*s %d", &ppid
) == 1))
2388 if(ppid
== process_id
)
2390 /* Recursively kill this child and its children. */
2391 kwsysProcessKill(pid
);
2405 #if defined(KWSYSPE_PS_COMMAND)
2406 /* Try running "ps" to get the process information. */
2407 FILE* ps
= popen(KWSYSPE_PS_COMMAND
, "r");
2409 /* Make sure the process started and provided a valid header. */
2410 if(ps
&& fscanf(ps
, "%*[^\n]\n") != EOF
)
2412 /* Look for processes whose parent is the process being killed. */
2414 while(fscanf(ps
, KWSYSPE_PS_FORMAT
, &pid
, &ppid
) == 2)
2416 if(ppid
== process_id
)
2418 /* Recursively kill this child and its children. */
2419 kwsysProcessKill(pid
);
2424 /* We are done with the ps process. */
2433 /*--------------------------------------------------------------------------*/
2434 /* Global set of executing processes for use by the signal handler.
2435 This global instance will be zero-initialized by the compiler. */
2436 typedef struct kwsysProcessInstances_s
2440 kwsysProcess
** Processes
;
2441 } kwsysProcessInstances
;
2442 static kwsysProcessInstances kwsysProcesses
;
2444 /* The old SIGCHLD handler. */
2445 static struct sigaction kwsysProcessesOldSigChldAction
;
2447 /*--------------------------------------------------------------------------*/
2448 static void kwsysProcessesUpdate(kwsysProcessInstances
* newProcesses
)
2450 /* Block SIGCHLD while we update the set of pipes to check.
2451 TODO: sigprocmask is undefined for threaded apps. See
2455 sigemptyset(&newset
);
2456 sigaddset(&newset
, SIGCHLD
);
2457 sigprocmask(SIG_BLOCK
, &newset
, &oldset
);
2459 /* Store the new set in that seen by the signal handler. */
2460 kwsysProcesses
= *newProcesses
;
2462 /* Restore the signal mask to the previous setting. */
2463 sigprocmask(SIG_SETMASK
, &oldset
, 0);
2466 /*--------------------------------------------------------------------------*/
2467 static int kwsysProcessesAdd(kwsysProcess
* cp
)
2469 /* Create a pipe through which the signal handler can notify the
2470 given process object that a child has exited. */
2472 /* Create the pipe. */
2479 /* Store the pipes now to be sure they are cleaned up later. */
2480 cp
->PipeReadEnds
[KWSYSPE_PIPE_SIGNAL
] = p
[0];
2481 cp
->SignalPipe
= p
[1];
2483 /* Switch the pipe to non-blocking mode so that reading a byte can
2484 be an atomic test-and-set. */
2485 if(!kwsysProcessSetNonBlocking(p
[0]) ||
2486 !kwsysProcessSetNonBlocking(p
[1]))
2491 /* The children do not need this pipe. Set close-on-exec flag on
2493 if((fcntl(p
[0], F_SETFD
, FD_CLOEXEC
) < 0) ||
2494 (fcntl(p
[1], F_SETFD
, FD_CLOEXEC
) < 0))
2500 /* Attempt to add the given signal pipe to the signal handler set. */
2503 /* Make sure there is enough space for the new signal pipe. */
2504 kwsysProcessInstances oldProcesses
= kwsysProcesses
;
2505 kwsysProcessInstances newProcesses
= oldProcesses
;
2506 if(oldProcesses
.Count
== oldProcesses
.Size
)
2508 /* Start with enough space for a small number of process instances
2509 and double the size each time more is needed. */
2510 newProcesses
.Size
= oldProcesses
.Size
? oldProcesses
.Size
*2 : 4;
2512 /* Try allocating the new block of memory. */
2513 if((newProcesses
.Processes
= ((kwsysProcess
**)
2514 malloc(newProcesses
.Size
*
2515 sizeof(kwsysProcess
*)))))
2517 /* Copy the old pipe set to the new memory. */
2518 if(oldProcesses
.Count
> 0)
2520 memcpy(newProcesses
.Processes
, oldProcesses
.Processes
,
2521 (oldProcesses
.Count
* sizeof(kwsysProcess
*)));
2526 /* Failed to allocate memory for the new signal pipe set. */
2531 /* Append the new signal pipe to the set. */
2532 newProcesses
.Processes
[newProcesses
.Count
++] = cp
;
2534 /* Store the new set in that seen by the signal handler. */
2535 kwsysProcessesUpdate(&newProcesses
);
2537 /* Free the original pipes if new ones were allocated. */
2538 if(newProcesses
.Processes
!= oldProcesses
.Processes
)
2540 free(oldProcesses
.Processes
);
2543 /* If this is the first process, enable the signal handler. */
2544 if(newProcesses
.Count
== 1)
2546 /* Install our handler for SIGCHLD. Repeat call until it is not
2548 struct sigaction newSigChldAction
;
2549 memset(&newSigChldAction
, 0, sizeof(struct sigaction
));
2550 #if KWSYSPE_USE_SIGINFO
2551 newSigChldAction
.sa_sigaction
= kwsysProcessesSignalHandler
;
2552 newSigChldAction
.sa_flags
= SA_NOCLDSTOP
| SA_SIGINFO
;
2554 newSigChldAction
.sa_flags
|= SA_RESTART
;
2557 newSigChldAction
.sa_handler
= kwsysProcessesSignalHandler
;
2558 newSigChldAction
.sa_flags
= SA_NOCLDSTOP
;
2560 while((sigaction(SIGCHLD
, &newSigChldAction
,
2561 &kwsysProcessesOldSigChldAction
) < 0) &&
2569 /*--------------------------------------------------------------------------*/
2570 static void kwsysProcessesRemove(kwsysProcess
* cp
)
2572 /* Attempt to remove the given signal pipe from the signal handler set. */
2574 /* Find the given process in the set. */
2575 kwsysProcessInstances newProcesses
= kwsysProcesses
;
2577 for(i
=0; i
< newProcesses
.Count
; ++i
)
2579 if(newProcesses
.Processes
[i
] == cp
)
2584 if(i
< newProcesses
.Count
)
2586 /* Remove the process from the set. */
2587 --newProcesses
.Count
;
2588 for(; i
< newProcesses
.Count
; ++i
)
2590 newProcesses
.Processes
[i
] = newProcesses
.Processes
[i
+1];
2593 /* If this was the last process, disable the signal handler. */
2594 if(newProcesses
.Count
== 0)
2596 /* Restore the SIGCHLD handler. Repeat call until it is not
2598 while((sigaction(SIGCHLD
, &kwsysProcessesOldSigChldAction
, 0) < 0) &&
2601 /* Free the table of process pointers since it is now empty.
2602 This is safe because the signal handler has been removed. */
2603 newProcesses
.Size
= 0;
2604 free(newProcesses
.Processes
);
2605 newProcesses
.Processes
= 0;
2608 /* Store the new set in that seen by the signal handler. */
2609 kwsysProcessesUpdate(&newProcesses
);
2613 /* Close the pipe through which the signal handler may have notified
2614 the given process object that a child has exited. */
2615 kwsysProcessCleanupDescriptor(&cp
->SignalPipe
);
2618 /*--------------------------------------------------------------------------*/
2619 static void kwsysProcessesSignalHandler(int signum
2620 #if KWSYSPE_USE_SIGINFO
2621 , siginfo_t
* info
, void* ucontext
2626 #if KWSYSPE_USE_SIGINFO
2631 /* Signal all process objects that a child has terminated. */
2634 for(i
=0; i
< kwsysProcesses
.Count
; ++i
)
2636 /* Set the pipe in a signalled state. */
2638 kwsysProcess
* cp
= kwsysProcesses
.Processes
[i
];
2639 read(cp
->PipeReadEnds
[KWSYSPE_PIPE_SIGNAL
], &buf
, 1);
2640 write(cp
->SignalPipe
, &buf
, 1);
2644 #if !KWSYSPE_USE_SIGINFO
2645 /* Re-Install our handler for SIGCHLD. Repeat call until it is not
2648 struct sigaction newSigChldAction
;
2649 memset(&newSigChldAction
, 0, sizeof(struct sigaction
));
2650 newSigChldAction
.sa_handler
= kwsysProcessesSignalHandler
;
2651 newSigChldAction
.sa_flags
= SA_NOCLDSTOP
;
2652 while((sigaction(SIGCHLD
, &newSigChldAction
,
2653 &kwsysProcessesOldSigChldAction
) < 0) &&
2659 /*--------------------------------------------------------------------------*/
2660 static int kwsysProcessAppendByte(char* local
,
2661 char** begin
, char** end
,
2664 /* Allocate space for the character. */
2665 if((*end
- *begin
) >= *size
)
2667 kwsysProcess_ptrdiff_t length
= *end
- *begin
;
2668 char* newBuffer
= (char*)malloc(*size
*2);
2673 memcpy(newBuffer
, *begin
, length
*sizeof(char));
2679 *end
= *begin
+ length
;
2683 /* Store the character. */
2688 /*--------------------------------------------------------------------------*/
2689 static int kwsysProcessAppendArgument(char** local
,
2690 char*** begin
, char*** end
,
2693 char** arg_begin
, char** arg_end
,
2696 /* Append a null-terminator to the argument string. */
2697 if(!kwsysProcessAppendByte(arg_local
, arg_begin
, arg_end
, arg_size
, '\0'))
2702 /* Allocate space for the argument pointer. */
2703 if((*end
- *begin
) >= *size
)
2705 kwsysProcess_ptrdiff_t length
= *end
- *begin
;
2706 char** newPointers
= (char**)malloc(*size
*2*sizeof(char*));
2711 memcpy(newPointers
, *begin
, length
*sizeof(char*));
2716 *begin
= newPointers
;
2717 *end
= *begin
+ length
;
2721 /* Allocate space for the argument string. */
2722 **end
= (char*)malloc(*arg_end
- *arg_begin
);
2728 /* Store the argument in the command array. */
2729 memcpy(**end
, *arg_begin
, *arg_end
- *arg_begin
);
2732 /* Reset the argument to be empty. */
2733 *arg_end
= *arg_begin
;
2738 /*--------------------------------------------------------------------------*/
2739 #define KWSYSPE_LOCAL_BYTE_COUNT 1024
2740 #define KWSYSPE_LOCAL_ARGS_COUNT 32
2741 static char** kwsysProcessParseVerbatimCommand(const char* command
)
2743 /* Create a buffer for argument pointers during parsing. */
2744 char* local_pointers
[KWSYSPE_LOCAL_ARGS_COUNT
];
2745 int pointers_size
= KWSYSPE_LOCAL_ARGS_COUNT
;
2746 char** pointer_begin
= local_pointers
;
2747 char** pointer_end
= pointer_begin
;
2749 /* Create a buffer for argument strings during parsing. */
2750 char local_buffer
[KWSYSPE_LOCAL_BYTE_COUNT
];
2751 int buffer_size
= KWSYSPE_LOCAL_BYTE_COUNT
;
2752 char* buffer_begin
= local_buffer
;
2753 char* buffer_end
= buffer_begin
;
2755 /* Parse the command string. Try to behave like a UNIX shell. */
2756 char** newCommand
= 0;
2757 const char* c
= command
;
2758 int in_argument
= 0;
2767 /* This character is escaped so do no special handling. */
2772 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2773 &buffer_end
, &buffer_size
, *c
))
2780 else if(*c
== '\\' && !in_single
)
2782 /* The next character should be escaped. */
2785 else if(*c
== '\'' && !in_double
)
2787 /* Enter or exit single-quote state. */
2801 else if(*c
== '"' && !in_single
)
2803 /* Enter or exit double-quote state. */
2817 else if(isspace((unsigned char) *c
))
2821 if(in_single
|| in_double
)
2823 /* This space belongs to a quoted argument. */
2824 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2825 &buffer_end
, &buffer_size
, *c
))
2833 /* This argument has been terminated by whitespace. */
2834 if(!kwsysProcessAppendArgument(local_pointers
, &pointer_begin
,
2835 &pointer_end
, &pointers_size
,
2836 local_buffer
, &buffer_begin
,
2837 &buffer_end
, &buffer_size
))
2848 /* This character belong to an argument. */
2853 if(!kwsysProcessAppendByte(local_buffer
, &buffer_begin
,
2854 &buffer_end
, &buffer_size
, *c
))
2862 /* Finish the last argument. */
2865 if(!kwsysProcessAppendArgument(local_pointers
, &pointer_begin
,
2866 &pointer_end
, &pointers_size
,
2867 local_buffer
, &buffer_begin
,
2868 &buffer_end
, &buffer_size
))
2874 /* If we still have memory allocate space for the new command
2878 kwsysProcess_ptrdiff_t n
= pointer_end
- pointer_begin
;
2879 newCommand
= (char**)malloc((n
+1)*sizeof(char*));
2884 /* Copy the arguments into the new command buffer. */
2885 kwsysProcess_ptrdiff_t n
= pointer_end
- pointer_begin
;
2886 memcpy(newCommand
, pointer_begin
, sizeof(char*)*n
);
2891 /* Free arguments already allocated. */
2892 while(pointer_end
!= pointer_begin
)
2894 free(*(--pointer_end
));
2898 /* Free temporary buffers. */
2899 if(pointer_begin
!= local_pointers
)
2901 free(pointer_begin
);
2903 if(buffer_begin
!= local_buffer
)
2908 /* Return the final command buffer. */