Imported Upstream version 2.8.11.2
[platform/upstream/cmake.git] / Source / kwsys / ProcessUNIX.c
1 /*============================================================================
2   KWSys - Kitware System Library
3   Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4
5   Distributed under the OSI-approved BSD License (the "License");
6   see accompanying file Copyright.txt for details.
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the License for more information.
11 ============================================================================*/
12 #include "kwsysPrivate.h"
13 #include KWSYS_HEADER(Process.h)
14 #include KWSYS_HEADER(System.h)
15
16 /* Work-around CMake dependency scanning limitation.  This must
17    duplicate the above list of headers.  */
18 #if 0
19 # include "Process.h.in"
20 # include "System.h.in"
21 #endif
22
23 /*
24
25 Implementation for UNIX
26
27 On UNIX, a child process is forked to exec the program.  Three output
28 pipes are read by the parent process using a select call to block
29 until data are ready.  Two of the pipes are stdout and stderr for the
30 child.  The third is a special pipe populated by a signal handler to
31 indicate that a child has terminated.  This is used in conjunction
32 with the timeout on the select call to implement a timeout for program
33 even when it closes stdout and stderr and at the same time avoiding
34 races.
35
36 */
37
38
39 /*
40
41 TODO:
42
43 We cannot create the pipeline of processes in suspended states.  How
44 do we cleanup processes already started when one fails to load?  Right
45 now we are just killing them, which is probably not the right thing to
46 do.
47
48 */
49
50 #if defined(__CYGWIN__)
51 /* Increase the file descriptor limit for select() before including
52    related system headers. (Default: 64) */
53 # define FD_SETSIZE 16384
54 #endif
55
56 #include <stddef.h>    /* ptrdiff_t */
57 #include <stdio.h>     /* snprintf */
58 #include <stdlib.h>    /* malloc, free */
59 #include <string.h>    /* strdup, strerror, memset */
60 #include <sys/time.h>  /* struct timeval */
61 #include <sys/types.h> /* pid_t, fd_set */
62 #include <sys/wait.h>  /* waitpid */
63 #include <sys/stat.h>  /* open mode */
64 #include <unistd.h>    /* pipe, close, fork, execvp, select, _exit */
65 #include <fcntl.h>     /* fcntl */
66 #include <errno.h>     /* errno */
67 #include <time.h>      /* gettimeofday */
68 #include <signal.h>    /* sigaction */
69 #include <dirent.h>    /* DIR, dirent */
70 #include <ctype.h>     /* isspace */
71
72 #if defined(__VMS)
73 # define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
74 #else
75 # define KWSYSPE_VMS_NONBLOCK
76 #endif
77
78 #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
79 typedef ptrdiff_t kwsysProcess_ptrdiff_t;
80 #else
81 typedef int kwsysProcess_ptrdiff_t;
82 #endif
83
84 #if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
85 typedef ssize_t kwsysProcess_ssize_t;
86 #else
87 typedef int kwsysProcess_ssize_t;
88 #endif
89
90 #if defined(__BEOS__) && !defined(__ZETA__) 
91 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
92 # include <be/kernel/OS.h>
93 static inline void kwsysProcess_usleep(unsigned int msec)
94 {
95   snooze(msec);
96 }
97 #else
98 # define kwsysProcess_usleep usleep
99 #endif
100
101 /*
102  * BeOS's select() works like WinSock: it's for networking only, and
103  * doesn't work with Unix file handles...socket and file handles are
104  * different namespaces (the same descriptor means different things in
105  * each context!)
106  *
107  * So on Unix-like systems where select() is flakey, we'll set the
108  * pipes' file handles to be non-blocking and just poll them directly
109  * without select().
110  */
111 #if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__)
112 # define KWSYSPE_USE_SELECT 1
113 #endif
114
115 /* Some platforms do not have siginfo on their signal handlers.  */
116 #if defined(SA_SIGINFO) && !defined(__BEOS__)
117 # define KWSYSPE_USE_SIGINFO 1
118 #endif
119
120 /* The number of pipes for the child's output.  The standard stdout
121    and stderr pipes are the first two.  One more pipe is used to
122    detect when the child process has terminated.  The third pipe is
123    not given to the child process, so it cannot close it until it
124    terminates.  */
125 #define KWSYSPE_PIPE_COUNT 3
126 #define KWSYSPE_PIPE_STDOUT 0
127 #define KWSYSPE_PIPE_STDERR 1
128 #define KWSYSPE_PIPE_SIGNAL 2
129
130 /* The maximum amount to read from a pipe at a time.  */
131 #define KWSYSPE_PIPE_BUFFER_SIZE 1024
132
133 /* Keep track of times using a signed representation.  Switch to the
134    native (possibly unsigned) representation only when calling native
135    functions.  */
136 typedef struct timeval kwsysProcessTimeNative;
137 typedef struct kwsysProcessTime_s kwsysProcessTime;
138 struct kwsysProcessTime_s
139 {
140   long tv_sec;
141   long tv_usec;
142 };
143
144 typedef struct kwsysProcessCreateInformation_s
145 {
146   int StdIn;
147   int StdOut;
148   int StdErr;
149   int ErrorPipe[2];
150 } kwsysProcessCreateInformation;
151
152 /*--------------------------------------------------------------------------*/
153 static int kwsysProcessInitialize(kwsysProcess* cp);
154 static void kwsysProcessCleanup(kwsysProcess* cp, int error);
155 static void kwsysProcessCleanupDescriptor(int* pfd);
156 static void kwsysProcessClosePipes(kwsysProcess* cp);
157 static int kwsysProcessSetNonBlocking(int fd);
158 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
159                               kwsysProcessCreateInformation* si, int* readEnd);
160 static void kwsysProcessDestroy(kwsysProcess* cp);
161 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
162 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]);
163 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
164                                       kwsysProcessTime* timeoutTime);
165 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
166                                       double* userTimeout,
167                                       kwsysProcessTimeNative* timeoutLength,
168                                       int zeroIsExpired);
169 static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
170 static double kwsysProcessTimeToDouble(kwsysProcessTime t);
171 static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
172 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
173 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
174 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
175 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
176 static void kwsysProcessChildErrorExit(int errorPipe);
177 static void kwsysProcessRestoreDefaultSignalHandlers(void);
178 static pid_t kwsysProcessFork(kwsysProcess* cp,
179                               kwsysProcessCreateInformation* si);
180 static void kwsysProcessKill(pid_t process_id);
181 #if defined(__VMS)
182 static int kwsysProcessSetVMSFeature(const char* name, int value);
183 #endif
184 static int kwsysProcessesAdd(kwsysProcess* cp);
185 static void kwsysProcessesRemove(kwsysProcess* cp);
186 #if KWSYSPE_USE_SIGINFO
187 static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
188                                         void* ucontext);
189 #else
190 static void kwsysProcessesSignalHandler(int signum);
191 #endif
192
193 /*--------------------------------------------------------------------------*/
194 /* Structure containing data used to implement the child's execution.  */
195 struct kwsysProcess_s
196 {
197   /* The command lines to execute.  */
198   char*** Commands;
199   int NumberOfCommands;
200
201   /* Descriptors for the read ends of the child's output pipes and
202      the signal pipe. */
203   int PipeReadEnds[KWSYSPE_PIPE_COUNT];
204
205   /* Write descriptor for child termination signal pipe.  */
206   int SignalPipe;
207
208   /* Buffer for pipe data.  */
209   char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
210
211   /* Process IDs returned by the calls to fork.  */
212   pid_t* ForkPIDs;
213
214   /* Flag for whether the children were terminated by a faild select.  */
215   int SelectError;
216
217   /* The timeout length.  */
218   double Timeout;
219
220   /* The working directory for the process. */
221   char* WorkingDirectory;
222
223   /* Whether to create the child as a detached process.  */
224   int OptionDetach;
225
226   /* Whether the child was created as a detached process.  */
227   int Detached;
228
229   /* Whether to treat command lines as verbatim.  */
230   int Verbatim;
231
232   /* Time at which the child started.  Negative for no timeout.  */
233   kwsysProcessTime StartTime;
234
235   /* Time at which the child will timeout.  Negative for no timeout.  */
236   kwsysProcessTime TimeoutTime;
237
238   /* Flag for whether the timeout expired.  */
239   int TimeoutExpired;
240
241   /* The number of pipes left open during execution.  */
242   int PipesLeft;
243
244 #if KWSYSPE_USE_SELECT
245   /* File descriptor set for call to select.  */
246   fd_set PipeSet;
247 #endif
248
249   /* The number of children still executing.  */
250   int CommandsLeft;
251
252   /* The current status of the child process. */
253   int State;
254
255   /* The exceptional behavior that terminated the child process, if
256    * any.  */
257   int ExitException;
258
259   /* The exit code of the child process.  */
260   int ExitCode;
261
262   /* The exit value of the child process, if any.  */
263   int ExitValue;
264
265   /* Whether the process was killed.  */
266   int Killed;
267
268   /* Buffer for error message in case of failure.  */
269   char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
270
271   /* Description for the ExitException.  */
272   char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
273
274   /* The exit codes of each child process in the pipeline.  */
275   int* CommandExitCodes;
276
277   /* Name of files to which stdin and stdout pipes are attached.  */
278   char* PipeFileSTDIN;
279   char* PipeFileSTDOUT;
280   char* PipeFileSTDERR;
281
282   /* Whether each pipe is shared with the parent process.  */
283   int PipeSharedSTDIN;
284   int PipeSharedSTDOUT;
285   int PipeSharedSTDERR;
286
287   /* Native pipes provided by the user.  */
288   int PipeNativeSTDIN[2];
289   int PipeNativeSTDOUT[2];
290   int PipeNativeSTDERR[2];
291
292   /* The real working directory of this process.  */
293   int RealWorkingDirectoryLength;
294   char* RealWorkingDirectory;
295 };
296
297 /*--------------------------------------------------------------------------*/
298 kwsysProcess* kwsysProcess_New(void)
299 {
300   /* Allocate a process control structure.  */
301   kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
302   if(!cp)
303     {
304     return 0;
305     }
306   memset(cp, 0, sizeof(kwsysProcess));
307
308   /* Share stdin with the parent process by default.  */
309   cp->PipeSharedSTDIN = 1;
310
311   /* No native pipes by default.  */
312   cp->PipeNativeSTDIN[0] = -1;
313   cp->PipeNativeSTDIN[1] = -1;
314   cp->PipeNativeSTDOUT[0] = -1;
315   cp->PipeNativeSTDOUT[1] = -1;
316   cp->PipeNativeSTDERR[0] = -1;
317   cp->PipeNativeSTDERR[1] = -1;
318
319   /* Set initial status.  */
320   cp->State = kwsysProcess_State_Starting;
321
322   return cp;
323 }
324
325 /*--------------------------------------------------------------------------*/
326 void kwsysProcess_Delete(kwsysProcess* cp)
327 {
328   /* Make sure we have an instance.  */
329   if(!cp)
330     {
331     return;
332     }
333
334   /* If the process is executing, wait for it to finish.  */
335   if(cp->State == kwsysProcess_State_Executing)
336     {
337     if(cp->Detached)
338       {
339       kwsysProcess_Disown(cp);
340       }
341     else
342       {
343       kwsysProcess_WaitForExit(cp, 0);
344       }
345     }
346
347   /* Free memory.  */
348   kwsysProcess_SetCommand(cp, 0);
349   kwsysProcess_SetWorkingDirectory(cp, 0);
350   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
351   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
352   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
353   if(cp->CommandExitCodes)
354     {
355     free(cp->CommandExitCodes);
356     }
357   free(cp);
358 }
359
360 /*--------------------------------------------------------------------------*/
361 int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
362 {
363   int i;
364   if(!cp)
365     {
366     return 0;
367     }
368   for(i=0; i < cp->NumberOfCommands; ++i)
369     {
370     char** c = cp->Commands[i];
371     while(*c)
372       {
373       free(*c++);
374       }
375     free(cp->Commands[i]);
376     }
377   cp->NumberOfCommands = 0;
378   if(cp->Commands)
379     {
380     free(cp->Commands);
381     cp->Commands = 0;
382     }
383   if(command)
384     {
385     return kwsysProcess_AddCommand(cp, command);
386     }
387   return 1;
388 }
389
390 /*--------------------------------------------------------------------------*/
391 int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
392 {
393   int newNumberOfCommands;
394   char*** newCommands;
395
396   /* Make sure we have a command to add.  */
397   if(!cp || !command || !*command)
398     {
399     return 0;
400     }
401
402   /* Allocate a new array for command pointers.  */
403   newNumberOfCommands = cp->NumberOfCommands + 1;
404   if(!(newCommands =
405        (char***)malloc(sizeof(char**) *(size_t)(newNumberOfCommands))))
406     {
407     /* Out of memory.  */
408     return 0;
409     }
410
411   /* Copy any existing commands into the new array.  */
412   {
413   int i;
414   for(i=0; i < cp->NumberOfCommands; ++i)
415     {
416     newCommands[i] = cp->Commands[i];
417     }
418   }
419
420   /* Add the new command.  */
421   if(cp->Verbatim)
422     {
423     /* In order to run the given command line verbatim we need to
424        parse it.  */
425     newCommands[cp->NumberOfCommands] =
426       kwsysSystem_Parse_CommandForUnix(*command, 0);
427     if(!newCommands[cp->NumberOfCommands] ||
428        !newCommands[cp->NumberOfCommands][0])
429       {
430       /* Out of memory or no command parsed.  */
431       free(newCommands);
432       return 0;
433       }
434     }
435   else
436     {
437     /* Copy each argument string individually.  */
438     char const* const* c = command;
439     kwsysProcess_ptrdiff_t n = 0;
440     kwsysProcess_ptrdiff_t i = 0;
441     while(*c++);
442     n = c - command - 1;
443     newCommands[cp->NumberOfCommands] =
444       (char**)malloc((size_t)(n+1)*sizeof(char*));
445     if(!newCommands[cp->NumberOfCommands])
446       {
447       /* Out of memory.  */
448       free(newCommands);
449       return 0;
450       }
451     for(i=0; i < n; ++i)
452       {
453       newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
454       if(!newCommands[cp->NumberOfCommands][i])
455         {
456         break;
457         }
458       }
459     if(i < n)
460       {
461       /* Out of memory.  */
462       for(;i > 0; --i)
463         {
464         free(newCommands[cp->NumberOfCommands][i-1]);
465         }
466       free(newCommands);
467       return 0;
468       }
469     newCommands[cp->NumberOfCommands][n] = 0;
470     }
471
472   /* Successfully allocated new command array.  Free the old array. */
473   free(cp->Commands);
474   cp->Commands = newCommands;
475   cp->NumberOfCommands = newNumberOfCommands;
476
477   return 1;
478 }
479
480 /*--------------------------------------------------------------------------*/
481 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
482 {
483   if(!cp)
484     {
485     return;
486     }
487   cp->Timeout = timeout;
488   if(cp->Timeout < 0)
489     {
490     cp->Timeout = 0;
491     }
492 }
493
494 /*--------------------------------------------------------------------------*/
495 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
496 {
497   if(!cp)
498     {
499     return 0;
500     }
501   if(cp->WorkingDirectory == dir)
502     {
503     return 1;
504     }
505   if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
506     {
507     return 1;
508     }
509   if(cp->WorkingDirectory)
510     {
511     free(cp->WorkingDirectory);
512     cp->WorkingDirectory = 0;
513     }
514   if(dir)
515     {
516     cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
517     if(!cp->WorkingDirectory)
518       {
519       return 0;
520       }
521     strcpy(cp->WorkingDirectory, dir);
522     }
523   return 1;
524 }
525
526 /*--------------------------------------------------------------------------*/
527 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
528 {
529   char** pfile;
530   if(!cp)
531     {
532     return 0;
533     }
534   switch(prPipe)
535     {
536     case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
537     case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
538     case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
539     default: return 0;
540     }
541   if(*pfile)
542     {
543     free(*pfile);
544     *pfile = 0;
545     }
546   if(file)
547     {
548     *pfile = malloc(strlen(file)+1);
549     if(!*pfile)
550       {
551       return 0;
552       }
553     strcpy(*pfile, file);
554     }
555
556   /* If we are redirecting the pipe, do not share it or use a native
557      pipe.  */
558   if(*pfile)
559     {
560     kwsysProcess_SetPipeNative(cp, prPipe, 0);
561     kwsysProcess_SetPipeShared(cp, prPipe, 0);
562     }
563   return 1;
564 }
565
566 /*--------------------------------------------------------------------------*/
567 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
568 {
569   if(!cp)
570     {
571     return;
572     }
573
574   switch(prPipe)
575     {
576     case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
577     case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
578     case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
579     default: return;
580     }
581
582   /* If we are sharing the pipe, do not redirect it to a file or use a
583      native pipe.  */
584   if(shared)
585     {
586     kwsysProcess_SetPipeFile(cp, prPipe, 0);
587     kwsysProcess_SetPipeNative(cp, prPipe, 0);
588     }
589 }
590
591 /*--------------------------------------------------------------------------*/
592 void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
593 {
594   int* pPipeNative = 0;
595
596   if(!cp)
597     {
598     return;
599     }
600
601   switch(prPipe)
602     {
603     case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
604     case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
605     case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
606     default: return;
607     }
608
609   /* Copy the native pipe descriptors provided.  */
610   if(p)
611     {
612     pPipeNative[0] = p[0];
613     pPipeNative[1] = p[1];
614     }
615   else
616     {
617     pPipeNative[0] = -1;
618     pPipeNative[1] = -1;
619     }
620
621   /* If we are using a native pipe, do not share it or redirect it to
622      a file.  */
623   if(p)
624     {
625     kwsysProcess_SetPipeFile(cp, prPipe, 0);
626     kwsysProcess_SetPipeShared(cp, prPipe, 0);
627     }
628 }
629
630 /*--------------------------------------------------------------------------*/
631 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
632 {
633   if(!cp)
634     {
635     return 0;
636     }
637
638   switch(optionId)
639     {
640     case kwsysProcess_Option_Detach: return cp->OptionDetach;
641     case kwsysProcess_Option_Verbatim: return cp->Verbatim;
642     default: return 0;
643     }
644 }
645
646 /*--------------------------------------------------------------------------*/
647 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
648 {
649   if(!cp)
650     {
651     return;
652     }
653
654   switch(optionId)
655     {
656     case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
657     case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
658     default: break;
659     }
660 }
661
662 /*--------------------------------------------------------------------------*/
663 int kwsysProcess_GetState(kwsysProcess* cp)
664 {
665   return cp? cp->State : kwsysProcess_State_Error;
666 }
667
668 /*--------------------------------------------------------------------------*/
669 int kwsysProcess_GetExitException(kwsysProcess* cp)
670 {
671   return cp? cp->ExitException : kwsysProcess_Exception_Other;
672 }
673
674 /*--------------------------------------------------------------------------*/
675 int kwsysProcess_GetExitCode(kwsysProcess* cp)
676 {
677   return cp? cp->ExitCode : 0;
678 }
679
680 /*--------------------------------------------------------------------------*/
681 int kwsysProcess_GetExitValue(kwsysProcess* cp)
682 {
683   return cp? cp->ExitValue : -1;
684 }
685
686 /*--------------------------------------------------------------------------*/
687 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
688 {
689   if(!cp)
690     {
691     return "Process management structure could not be allocated";
692     }
693   else if(cp->State == kwsysProcess_State_Error)
694     {
695     return cp->ErrorMessage;
696     }
697   return "Success";
698 }
699
700 /*--------------------------------------------------------------------------*/
701 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
702 {
703   if(!cp)
704     {
705     return "GetExceptionString called with NULL process management structure";
706     }
707   else if(cp->State == kwsysProcess_State_Exception)
708     {
709     return cp->ExitExceptionString;
710     }
711   return "No exception";
712 }
713
714 /*--------------------------------------------------------------------------*/
715 void kwsysProcess_Execute(kwsysProcess* cp)
716 {
717   int i;
718   kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
719
720   /* Do not execute a second copy simultaneously.  */
721   if(!cp || cp->State == kwsysProcess_State_Executing)
722     {
723     return;
724     }
725
726   /* Make sure we have something to run.  */
727   if(cp->NumberOfCommands < 1)
728     {
729     strcpy(cp->ErrorMessage, "No command");
730     cp->State = kwsysProcess_State_Error;
731     return;
732     }
733
734   /* Initialize the control structure for a new process.  */
735   if(!kwsysProcessInitialize(cp))
736     {
737     strcpy(cp->ErrorMessage, "Out of memory");
738     cp->State = kwsysProcess_State_Error;
739     return;
740     }
741
742 #if defined(__VMS)
743   /* Make sure pipes behave like streams on VMS.  */
744   if(!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1))
745     {
746     kwsysProcessCleanup(cp, 1);
747     return;
748     }
749 #endif
750
751   /* Save the real working directory of this process and change to
752      the working directory for the child processes.  This is needed
753      to make pipe file paths evaluate correctly.  */
754   if(cp->WorkingDirectory)
755     {
756     int r;
757     if(!getcwd(cp->RealWorkingDirectory,
758                (size_t)(cp->RealWorkingDirectoryLength)))
759       {
760       kwsysProcessCleanup(cp, 1);
761       return;
762       }
763
764     /* Some platforms specify that the chdir call may be
765        interrupted.  Repeat the call until it finishes.  */
766     while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
767     if(r < 0)
768       {
769       kwsysProcessCleanup(cp, 1);
770       return;
771       }
772     }
773
774   /* If not running a detached child, add this object to the global
775      set of process objects that wish to be notified when a child
776      exits.  */
777   if(!cp->OptionDetach)
778     {
779     if(!kwsysProcessesAdd(cp))
780       {
781       kwsysProcessCleanup(cp, 1);
782       return;
783       }
784     }
785
786   /* Setup the stderr pipe to be shared by all processes.  */
787   {
788   /* Create the pipe.  */
789   int p[2];
790   if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
791     {
792     kwsysProcessCleanup(cp, 1);
793     return;
794     }
795
796   /* Store the pipe.  */
797   cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
798   si.StdErr = p[1];
799
800   /* Set close-on-exec flag on the pipe's ends.  */
801   if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
802      (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
803     {
804     kwsysProcessCleanup(cp, 1);
805     kwsysProcessCleanupDescriptor(&si.StdErr);
806     return;
807     }
808
809   /* Set to non-blocking in case select lies, or for the polling
810      implementation.  */
811   if(!kwsysProcessSetNonBlocking(p[0]))
812     {
813     kwsysProcessCleanup(cp, 1);
814     kwsysProcessCleanupDescriptor(&si.StdErr);
815     return;
816     }
817   }
818
819   /* Replace the stderr pipe with a file if requested.  In this case
820      the select call will report that stderr is closed immediately.  */
821   if(cp->PipeFileSTDERR)
822     {
823     if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
824       {
825       kwsysProcessCleanup(cp, 1);
826       kwsysProcessCleanupDescriptor(&si.StdErr);
827       return;
828       }
829     }
830
831   /* Replace the stderr pipe with the parent's if requested.  In this
832      case the select call will report that stderr is closed
833      immediately.  */
834   if(cp->PipeSharedSTDERR)
835     {
836     kwsysProcessCleanupDescriptor(&si.StdErr);
837     si.StdErr = 2;
838     }
839
840   /* Replace the stderr pipe with the native pipe provided if any.  In
841      this case the select call will report that stderr is closed
842      immediately.  */
843   if(cp->PipeNativeSTDERR[1] >= 0)
844     {
845     if(!kwsysProcessSetupOutputPipeNative(&si.StdErr, cp->PipeNativeSTDERR))
846       {
847       kwsysProcessCleanup(cp, 1);
848       kwsysProcessCleanupDescriptor(&si.StdErr);
849       return;
850       }
851     }
852
853   /* The timeout period starts now.  */
854   cp->StartTime = kwsysProcessTimeGetCurrent();
855   cp->TimeoutTime.tv_sec = -1;
856   cp->TimeoutTime.tv_usec = -1;
857
858   /* Create the pipeline of processes.  */
859   {
860   int readEnd = -1;
861   int failed = 0;
862   for(i=0; i < cp->NumberOfCommands; ++i)
863     {
864     if(!kwsysProcessCreate(cp, i, &si, &readEnd))
865       {
866       failed = 1;
867       }
868
869     /* Set the output pipe of the last process to be non-blocking in
870        case select lies, or for the polling implementation.  */
871     if(i == (cp->NumberOfCommands-1) && !kwsysProcessSetNonBlocking(readEnd))
872       {
873       failed = 1;
874       }
875
876     if(failed)
877       {
878       kwsysProcessCleanup(cp, 1);
879
880       /* Release resources that may have been allocated for this
881          process before an error occurred.  */
882       kwsysProcessCleanupDescriptor(&readEnd);
883       if(si.StdIn != 0)
884         {
885         kwsysProcessCleanupDescriptor(&si.StdIn);
886         }
887       if(si.StdOut != 1)
888         {
889         kwsysProcessCleanupDescriptor(&si.StdOut);
890         }
891       if(si.StdErr != 2)
892         {
893         kwsysProcessCleanupDescriptor(&si.StdErr);
894         }
895       kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
896       kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
897       return;
898       }
899     }
900   /* Save a handle to the output pipe for the last process.  */
901   cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
902   }
903
904   /* The parent process does not need the output pipe write ends.  */
905   if(si.StdErr != 2)
906     {
907     kwsysProcessCleanupDescriptor(&si.StdErr);
908     }
909
910   /* Restore the working directory. */
911   if(cp->RealWorkingDirectory)
912     {
913     /* Some platforms specify that the chdir call may be
914        interrupted.  Repeat the call until it finishes.  */
915     while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
916     free(cp->RealWorkingDirectory);
917     cp->RealWorkingDirectory = 0;
918     }
919
920   /* All the pipes are now open.  */
921   cp->PipesLeft = KWSYSPE_PIPE_COUNT;
922
923   /* The process has now started.  */
924   cp->State = kwsysProcess_State_Executing;
925   cp->Detached = cp->OptionDetach;
926 }
927
928 /*--------------------------------------------------------------------------*/
929 kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
930 {
931   /* Make sure a detached child process is running.  */
932   if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
933      cp->TimeoutExpired || cp->Killed)
934     {
935     return;
936     }
937
938   /* Close all the pipes safely.  */
939   kwsysProcessClosePipes(cp);
940
941   /* We will not wait for exit, so cleanup now.  */
942   kwsysProcessCleanup(cp, 0);
943
944   /* The process has been disowned.  */
945   cp->State = kwsysProcess_State_Disowned;
946 }
947
948 /*--------------------------------------------------------------------------*/
949 typedef struct kwsysProcessWaitData_s
950 {
951   int Expired;
952   int PipeId;
953   int User;
954   double* UserTimeout;
955   kwsysProcessTime TimeoutTime;
956 } kwsysProcessWaitData;
957 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
958                                    kwsysProcessWaitData* wd);
959
960 /*--------------------------------------------------------------------------*/
961 int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
962                              double* userTimeout)
963 {
964   kwsysProcessTime userStartTime = {0, 0};
965   kwsysProcessWaitData wd =
966     {
967       0,
968       kwsysProcess_Pipe_None,
969       0,
970       0,
971       {0, 0}
972     };
973   wd.UserTimeout = userTimeout;
974   /* Make sure we are executing a process.  */
975   if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
976      cp->TimeoutExpired)
977     {
978     return kwsysProcess_Pipe_None;
979     }
980
981   /* Record the time at which user timeout period starts.  */
982   if(userTimeout)
983     {
984     userStartTime = kwsysProcessTimeGetCurrent();
985     }
986
987   /* Calculate the time at which a timeout will expire, and whether it
988      is the user or process timeout.  */
989   wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
990                                        &wd.TimeoutTime);
991
992   /* Data can only be available when pipes are open.  If the process
993      is not running, cp->PipesLeft will be 0.  */
994   while(cp->PipesLeft > 0 &&
995         !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
996
997   /* Update the user timeout.  */
998   if(userTimeout)
999     {
1000     kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
1001     kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
1002                                                            userStartTime);
1003     double d = kwsysProcessTimeToDouble(difference);
1004     *userTimeout -= d;
1005     if(*userTimeout < 0)
1006       {
1007       *userTimeout = 0;
1008       }
1009     }
1010
1011   /* Check what happened.  */
1012   if(wd.PipeId)
1013     {
1014     /* Data are ready on a pipe.  */
1015     return wd.PipeId;
1016     }
1017   else if(wd.Expired)
1018     {
1019     /* A timeout has expired.  */
1020     if(wd.User)
1021       {
1022       /* The user timeout has expired.  It has no time left.  */
1023       return kwsysProcess_Pipe_Timeout;
1024       }
1025     else
1026       {
1027       /* The process timeout has expired.  Kill the children now.  */
1028       kwsysProcess_Kill(cp);
1029       cp->Killed = 0;
1030       cp->TimeoutExpired = 1;
1031       return kwsysProcess_Pipe_None;
1032       }
1033     }
1034   else
1035     {
1036     /* No pipes are left open.  */
1037     return kwsysProcess_Pipe_None;
1038     }
1039 }
1040
1041 /*--------------------------------------------------------------------------*/
1042 static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
1043                                    kwsysProcessWaitData* wd)
1044 {
1045   int i;
1046   kwsysProcessTimeNative timeoutLength;
1047
1048 #if KWSYSPE_USE_SELECT
1049   int numReady = 0;
1050   int max = -1;
1051   kwsysProcessTimeNative* timeout = 0;
1052
1053   /* Check for any open pipes with data reported ready by the last
1054      call to select.  According to "man select_tut" we must deal
1055      with all descriptors reported by a call to select before
1056      passing them to another select call.  */
1057   for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1058     {
1059     if(cp->PipeReadEnds[i] >= 0 &&
1060        FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1061       {
1062       kwsysProcess_ssize_t n;
1063
1064       /* We are handling this pipe now.  Remove it from the set.  */
1065       FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1066
1067       /* The pipe is ready to read without blocking.  Keep trying to
1068          read until the operation is not interrupted.  */
1069       while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
1070                        KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
1071       if(n > 0)
1072         {
1073         /* We have data on this pipe.  */
1074         if(i == KWSYSPE_PIPE_SIGNAL)
1075           {
1076           /* A child process has terminated.  */
1077           kwsysProcessDestroy(cp);
1078           }
1079         else if(data && length)
1080           {
1081           /* Report this data.  */
1082           *data = cp->PipeBuffer;
1083           *length = (int)(n);
1084           switch(i)
1085             {
1086             case KWSYSPE_PIPE_STDOUT:
1087               wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1088             case KWSYSPE_PIPE_STDERR:
1089               wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1090             };
1091           return 1;
1092           }
1093         }
1094       else if(n < 0 && errno == EAGAIN)
1095         {
1096         /* No data are really ready.  The select call lied.  See the
1097            "man select" page on Linux for cases when this occurs.  */
1098         }
1099       else
1100         {
1101         /* We are done reading from this pipe.  */
1102         kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1103         --cp->PipesLeft;
1104         }
1105       }
1106     }
1107
1108   /* If we have data, break early.  */
1109   if(wd->PipeId)
1110     {
1111     return 1;
1112     }
1113
1114   /* Make sure the set is empty (it should always be empty here
1115      anyway).  */
1116   FD_ZERO(&cp->PipeSet);
1117
1118   /* Setup a timeout if required.  */
1119   if(wd->TimeoutTime.tv_sec < 0)
1120     {
1121     timeout = 0;
1122     }
1123   else
1124     {
1125     timeout = &timeoutLength;
1126     }
1127   if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
1128                                 wd->User?wd->UserTimeout:0,
1129                                 &timeoutLength, 0))
1130     {
1131     /* Timeout has already expired.  */
1132     wd->Expired = 1;
1133     return 1;
1134     }
1135
1136   /* Add the pipe reading ends that are still open.  */
1137   max = -1;
1138   for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1139     {
1140     if(cp->PipeReadEnds[i] >= 0)
1141       {
1142       FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
1143       if(cp->PipeReadEnds[i] > max)
1144         {
1145         max = cp->PipeReadEnds[i];
1146         }
1147       }
1148     }
1149
1150   /* Make sure we have a non-empty set.  */
1151   if(max < 0)
1152     {
1153     /* All pipes have closed.  Child has terminated.  */
1154     return 1;
1155     }
1156
1157   /* Run select to block until data are available.  Repeat call
1158      until it is not interrupted.  */
1159   while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
1160         (errno == EINTR));
1161
1162   /* Check result of select.  */
1163   if(numReady == 0)
1164     {
1165     /* Select's timeout expired.  */
1166     wd->Expired = 1;
1167     return 1;
1168     }
1169   else if(numReady < 0)
1170     {
1171     /* Select returned an error.  Leave the error description in the
1172        pipe buffer.  */
1173     strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1174
1175     /* Kill the children now.  */
1176     kwsysProcess_Kill(cp);
1177     cp->Killed = 0;
1178     cp->SelectError = 1;
1179     }
1180
1181   return 0;
1182 #else
1183   /* Poll pipes for data since we do not have select.  */
1184   for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1185     {
1186     if(cp->PipeReadEnds[i] >= 0)
1187       {
1188       const int fd = cp->PipeReadEnds[i];
1189       int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
1190       if(n > 0)
1191         {
1192         /* We have data on this pipe.  */
1193         if(i == KWSYSPE_PIPE_SIGNAL)
1194           {
1195           /* A child process has terminated.  */
1196           kwsysProcessDestroy(cp);
1197           }
1198         else if(data && length)
1199           {
1200           /* Report this data.  */
1201           *data = cp->PipeBuffer;
1202           *length = n;
1203           switch(i)
1204             {
1205             case KWSYSPE_PIPE_STDOUT:
1206               wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
1207             case KWSYSPE_PIPE_STDERR:
1208               wd->PipeId = kwsysProcess_Pipe_STDERR; break;
1209             };
1210           }
1211         return 1;
1212         }
1213       else if (n == 0)  /* EOF */
1214         {
1215         /* We are done reading from this pipe.  */
1216 #if defined(__VMS)
1217         if(!cp->CommandsLeft)
1218 #endif
1219           {
1220           kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1221           --cp->PipesLeft;
1222           }
1223         }
1224       else if (n < 0)  /* error */
1225         {
1226 #if defined(__VMS)
1227         if(!cp->CommandsLeft)
1228           {
1229           kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1230           --cp->PipesLeft;
1231           }
1232         else
1233 #endif
1234         if((errno != EINTR) && (errno != EAGAIN))
1235           {
1236           strncpy(cp->ErrorMessage,strerror(errno),
1237                   KWSYSPE_PIPE_BUFFER_SIZE);
1238           /* Kill the children now.  */
1239           kwsysProcess_Kill(cp);
1240           cp->Killed = 0;
1241           cp->SelectError = 1;
1242           return 1;
1243           }
1244         }
1245       }
1246     }
1247
1248   /* If we have data, break early.  */
1249   if(wd->PipeId)
1250     {
1251     return 1;
1252     }
1253
1254   if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
1255                                 &timeoutLength, 1))
1256     {
1257     /* Timeout has already expired.  */
1258     wd->Expired = 1;
1259     return 1;
1260     }
1261
1262   /* Sleep a little, try again. */
1263   {
1264   unsigned int msec = ((timeoutLength.tv_sec * 1000) +
1265                        (timeoutLength.tv_usec / 1000));
1266   if (msec > 100000)
1267     {
1268     msec = 100000;  /* do not sleep more than 100 milliseconds at a time */
1269     }
1270   kwsysProcess_usleep(msec);
1271   }
1272   return 0;
1273 #endif
1274 }
1275
1276 /*--------------------------------------------------------------------------*/
1277 int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
1278 {
1279   int status = 0;
1280   int prPipe = 0;
1281
1282   /* Make sure we are executing a process.  */
1283   if(!cp || cp->State != kwsysProcess_State_Executing)
1284     {
1285     return 1;
1286     }
1287
1288   /* Wait for all the pipes to close.  Ignore all data.  */
1289   while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
1290     {
1291     if(prPipe == kwsysProcess_Pipe_Timeout)
1292       {
1293       return 0;
1294       }
1295     }
1296
1297   /* Check if there was an error in one of the waitpid calls.  */
1298   if(cp->State == kwsysProcess_State_Error)
1299     {
1300     /* The error message is already in its buffer.  Tell
1301        kwsysProcessCleanup to not create it.  */
1302     kwsysProcessCleanup(cp, 0);
1303     return 1;
1304     }
1305
1306   /* Check whether the child reported an error invoking the process.  */
1307   if(cp->SelectError)
1308     {
1309     /* The error message is already in its buffer.  Tell
1310        kwsysProcessCleanup to not create it.  */
1311     kwsysProcessCleanup(cp, 0);
1312     cp->State = kwsysProcess_State_Error;
1313     return 1;
1314     }
1315
1316   /* Use the status of the last process in the pipeline.  */
1317   status = cp->CommandExitCodes[cp->NumberOfCommands-1];
1318
1319   /* Determine the outcome.  */
1320   if(cp->Killed)
1321     {
1322     /* We killed the child.  */
1323     cp->State = kwsysProcess_State_Killed;
1324     }
1325   else if(cp->TimeoutExpired)
1326     {
1327     /* The timeout expired.  */
1328     cp->State = kwsysProcess_State_Expired;
1329     }
1330   else if(WIFEXITED(status))
1331     {
1332     /* The child exited normally.  */
1333     cp->State = kwsysProcess_State_Exited;
1334     cp->ExitException = kwsysProcess_Exception_None;
1335     cp->ExitCode = status;
1336     cp->ExitValue = (int)WEXITSTATUS(status);
1337     }
1338   else if(WIFSIGNALED(status))
1339     {
1340     /* The child received an unhandled signal.  */
1341     cp->State = kwsysProcess_State_Exception;
1342     cp->ExitCode = status;
1343     kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
1344     }
1345   else
1346     {
1347     /* Error getting the child return code.  */
1348     strcpy(cp->ErrorMessage, "Error getting child return code.");
1349     cp->State = kwsysProcess_State_Error;
1350     }
1351
1352   /* Normal cleanup.  */
1353   kwsysProcessCleanup(cp, 0);
1354   return 1;
1355 }
1356
1357 /*--------------------------------------------------------------------------*/
1358 void kwsysProcess_Kill(kwsysProcess* cp)
1359 {
1360   int i;
1361
1362   /* Make sure we are executing a process.  */
1363   if(!cp || cp->State != kwsysProcess_State_Executing)
1364     {
1365     return;
1366     }
1367
1368   /* First close the child exit report pipe write end to avoid causing a
1369      SIGPIPE when the child terminates and our signal handler tries to
1370      report it after we have already closed the read end.  */
1371   kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1372
1373 #if !defined(__APPLE__)
1374   /* Close all the pipe read ends.  Do this before killing the
1375      children because Cygwin has problems killing processes that are
1376      blocking to wait for writing to their output pipes.  */
1377   kwsysProcessClosePipes(cp);
1378 #endif
1379
1380   /* Kill the children.  */
1381   cp->Killed = 1;
1382   for(i=0; i < cp->NumberOfCommands; ++i)
1383     {
1384     int status;
1385     if(cp->ForkPIDs[i])
1386       {
1387       /* Kill the child.  */
1388       kwsysProcessKill(cp->ForkPIDs[i]);
1389
1390       /* Reap the child.  Keep trying until the call is not
1391          interrupted.  */
1392       while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
1393       }
1394     }
1395
1396 #if defined(__APPLE__)
1397   /* Close all the pipe read ends.  Do this after killing the
1398      children because OS X has problems closing pipe read ends whose
1399      pipes are full and still have an open write end.  */
1400   kwsysProcessClosePipes(cp);
1401 #endif
1402
1403   cp->CommandsLeft = 0;
1404 }
1405
1406 /*--------------------------------------------------------------------------*/
1407 /* Initialize a process control structure for kwsysProcess_Execute.  */
1408 static int kwsysProcessInitialize(kwsysProcess* cp)
1409 {
1410   int i;
1411   for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1412     {
1413     cp->PipeReadEnds[i] = -1;
1414     }
1415   cp->SignalPipe = -1;
1416   cp->SelectError = 0;
1417   cp->StartTime.tv_sec = -1;
1418   cp->StartTime.tv_usec = -1;
1419   cp->TimeoutTime.tv_sec = -1;
1420   cp->TimeoutTime.tv_usec = -1;
1421   cp->TimeoutExpired = 0;
1422   cp->PipesLeft = 0;
1423   cp->CommandsLeft = 0;
1424 #if KWSYSPE_USE_SELECT
1425   FD_ZERO(&cp->PipeSet);
1426 #endif
1427   cp->State = kwsysProcess_State_Starting;
1428   cp->Killed = 0;
1429   cp->ExitException = kwsysProcess_Exception_None;
1430   cp->ExitCode = 1;
1431   cp->ExitValue = 1;
1432   cp->ErrorMessage[0] = 0;
1433   strcpy(cp->ExitExceptionString, "No exception");
1434
1435   if(cp->ForkPIDs)
1436     {
1437     free(cp->ForkPIDs);
1438     }
1439   cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
1440   if(!cp->ForkPIDs)
1441     {
1442     return 0;
1443     }
1444   memset(cp->ForkPIDs, 0, sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
1445
1446   if(cp->CommandExitCodes)
1447     {
1448     free(cp->CommandExitCodes);
1449     }
1450   cp->CommandExitCodes = (int*)malloc(sizeof(int)*
1451                                       (size_t)(cp->NumberOfCommands));
1452   if(!cp->CommandExitCodes)
1453     {
1454     return 0;
1455     }
1456   memset(cp->CommandExitCodes, 0, sizeof(int)*(size_t)(cp->NumberOfCommands));
1457
1458   /* Allocate memory to save the real working directory.  */
1459   if ( cp->WorkingDirectory )
1460     {
1461 #if defined(MAXPATHLEN)
1462     cp->RealWorkingDirectoryLength = MAXPATHLEN;
1463 #elif defined(PATH_MAX)
1464     cp->RealWorkingDirectoryLength = PATH_MAX;
1465 #else
1466     cp->RealWorkingDirectoryLength = 4096;
1467 #endif
1468     cp->RealWorkingDirectory =
1469       malloc((size_t)(cp->RealWorkingDirectoryLength));
1470     if(!cp->RealWorkingDirectory)
1471       {
1472       return 0;
1473       }
1474     }
1475
1476   return 1;
1477 }
1478
1479 /*--------------------------------------------------------------------------*/
1480 /* Free all resources used by the given kwsysProcess instance that were
1481    allocated by kwsysProcess_Execute.  */
1482 static void kwsysProcessCleanup(kwsysProcess* cp, int error)
1483 {
1484   int i;
1485
1486   if(error)
1487     {
1488     /* We are cleaning up due to an error.  Report the error message
1489        if one has not been provided already.  */
1490     if(cp->ErrorMessage[0] == 0)
1491       {
1492       strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1493       }
1494
1495     /* Set the error state.  */
1496     cp->State = kwsysProcess_State_Error;
1497
1498     /* Kill any children already started.  */
1499     if(cp->ForkPIDs)
1500       {
1501       int status;
1502       for(i=0; i < cp->NumberOfCommands; ++i)
1503         {
1504         if(cp->ForkPIDs[i])
1505           {
1506           /* Kill the child.  */
1507           kwsysProcessKill(cp->ForkPIDs[i]);
1508
1509           /* Reap the child.  Keep trying until the call is not
1510              interrupted.  */
1511           while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
1512                 (errno == EINTR));
1513           }
1514         }
1515       }
1516
1517     /* Restore the working directory.  */
1518     if(cp->RealWorkingDirectory)
1519       {
1520       while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
1521       }
1522     }
1523
1524   /* If not creating a detached child, remove this object from the
1525      global set of process objects that wish to be notified when a
1526      child exits.  */
1527   if(!cp->OptionDetach)
1528     {
1529     kwsysProcessesRemove(cp);
1530     }
1531
1532   /* Free memory.  */
1533   if(cp->ForkPIDs)
1534     {
1535     free(cp->ForkPIDs);
1536     cp->ForkPIDs = 0;
1537     }
1538   if(cp->RealWorkingDirectory)
1539     {
1540     free(cp->RealWorkingDirectory);
1541     cp->RealWorkingDirectory = 0;
1542     }
1543
1544   /* Close pipe handles.  */
1545   for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1546     {
1547     kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1548     }
1549 }
1550
1551 /*--------------------------------------------------------------------------*/
1552 /* Close the given file descriptor if it is open.  Reset its value to -1.  */
1553 static void kwsysProcessCleanupDescriptor(int* pfd)
1554 {
1555   if(pfd && *pfd >= 0)
1556     {
1557     /* Keep trying to close until it is not interrupted by a
1558      * signal.  */
1559     while((close(*pfd) < 0) && (errno == EINTR));
1560     *pfd = -1;
1561     }
1562 }
1563
1564 /*--------------------------------------------------------------------------*/
1565 static void kwsysProcessClosePipes(kwsysProcess* cp)
1566 {
1567   int i;
1568
1569   /* Close any pipes that are still open.  */
1570   for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
1571     {
1572     if(cp->PipeReadEnds[i] >= 0)
1573       {
1574 #if KWSYSPE_USE_SELECT
1575       /* If the pipe was reported by the last call to select, we must
1576          read from it.  This is needed to satisfy the suggestions from
1577          "man select_tut" and is not needed for the polling
1578          implementation.  Ignore the data.  */
1579       if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
1580         {
1581         /* We are handling this pipe now.  Remove it from the set.  */
1582         FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
1583
1584         /* The pipe is ready to read without blocking.  Keep trying to
1585            read until the operation is not interrupted.  */
1586         while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
1587                     KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
1588         }
1589 #endif
1590
1591       /* We are done reading from this pipe.  */
1592       kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
1593       --cp->PipesLeft;
1594       }
1595     }
1596 }
1597
1598 /*--------------------------------------------------------------------------*/
1599 static int kwsysProcessSetNonBlocking(int fd)
1600 {
1601   int flags = fcntl(fd, F_GETFL);
1602   if(flags >= 0)
1603     {
1604     flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
1605     }
1606   return flags >= 0;
1607 }
1608
1609 /*--------------------------------------------------------------------------*/
1610 #if defined(__VMS)
1611 int decc$set_child_standard_streams(int fd1, int fd2, int fd3);
1612 #endif
1613
1614 /*--------------------------------------------------------------------------*/
1615 static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
1616                               kwsysProcessCreateInformation* si, int* readEnd)
1617 {
1618   /* Setup the process's stdin.  */
1619   if(prIndex > 0)
1620     {
1621     si->StdIn = *readEnd;
1622     *readEnd = 0;
1623     }
1624   else if(cp->PipeFileSTDIN)
1625     {
1626     /* Open a file for the child's stdin to read.  */
1627     si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
1628     if(si->StdIn < 0)
1629       {
1630       return 0;
1631       }
1632
1633     /* Set close-on-exec flag on the pipe's end.  */
1634     if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
1635       {
1636       return 0;
1637       }
1638     }
1639   else if(cp->PipeSharedSTDIN)
1640     {
1641     si->StdIn = 0;
1642     }
1643   else if(cp->PipeNativeSTDIN[0] >= 0)
1644     {
1645     si->StdIn = cp->PipeNativeSTDIN[0];
1646
1647     /* Set close-on-exec flag on the pipe's ends.  The read end will
1648        be dup2-ed into the stdin descriptor after the fork but before
1649        the exec.  */
1650     if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
1651        (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
1652       {
1653       return 0;
1654       }
1655     }
1656   else
1657     {
1658     si->StdIn = -1;
1659     }
1660
1661   /* Setup the process's stdout.  */
1662   {
1663   /* Create the pipe.  */
1664   int p[2];
1665   if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
1666     {
1667     return 0;
1668     }
1669   *readEnd = p[0];
1670   si->StdOut = p[1];
1671
1672   /* Set close-on-exec flag on the pipe's ends.  */
1673   if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
1674      (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
1675     {
1676     return 0;
1677     }
1678   }
1679
1680   /* Replace the stdout pipe with a file if requested.  In this case
1681      the select call will report that stdout is closed immediately.  */
1682   if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
1683     {
1684     if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
1685       {
1686       return 0;
1687       }
1688     }
1689
1690   /* Replace the stdout pipe with the parent's if requested.  In this
1691      case the select call will report that stderr is closed
1692      immediately.  */
1693   if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
1694     {
1695     kwsysProcessCleanupDescriptor(&si->StdOut);
1696     si->StdOut = 1;
1697     }
1698
1699   /* Replace the stdout pipe with the native pipe provided if any.  In
1700      this case the select call will report that stdout is closed
1701      immediately.  */
1702   if(prIndex == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1] >= 0)
1703     {
1704     if(!kwsysProcessSetupOutputPipeNative(&si->StdOut, cp->PipeNativeSTDOUT))
1705       {
1706       return 0;
1707       }
1708     }
1709
1710   /* Create the error reporting pipe.  */
1711   if(pipe(si->ErrorPipe) < 0)
1712     {
1713     return 0;
1714     }
1715
1716   /* Set close-on-exec flag on the error pipe's write end.  */
1717   if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
1718     {
1719     return 0;
1720     }
1721
1722   /* Fork off a child process.  */
1723 #if defined(__VMS)
1724   /* VMS needs vfork and execvp to be in the same function because
1725      they use setjmp/longjmp to run the child startup code in the
1726      parent!  TODO: OptionDetach.  */
1727   cp->ForkPIDs[prIndex] = vfork();
1728 #else
1729   cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
1730 #endif
1731   if(cp->ForkPIDs[prIndex] < 0)
1732     {
1733     return 0;
1734     }
1735
1736   if(cp->ForkPIDs[prIndex] == 0)
1737     {
1738 #if defined(__VMS)
1739     /* Specify standard pipes for child process.  */
1740     decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr);
1741 #else
1742     /* Close the read end of the error reporting pipe.  */
1743     close(si->ErrorPipe[0]);
1744
1745     /* Setup the stdin, stdout, and stderr pipes.  */
1746     if(si->StdIn > 0)
1747       {
1748       dup2(si->StdIn, 0);
1749       }
1750     else if(si->StdIn < 0)
1751       {
1752       close(0);
1753       }
1754     if(si->StdOut != 1)
1755       {
1756       dup2(si->StdOut, 1);
1757       }
1758     if(si->StdErr != 2)
1759       {
1760       dup2(si->StdErr, 2);
1761       }
1762
1763     /* Clear the close-on-exec flag for stdin, stdout, and stderr.
1764        All other pipe handles will be closed when exec succeeds.  */
1765     fcntl(0, F_SETFD, 0);
1766     fcntl(1, F_SETFD, 0);
1767     fcntl(2, F_SETFD, 0);
1768
1769     /* Restore all default signal handlers. */
1770     kwsysProcessRestoreDefaultSignalHandlers();
1771 #endif
1772
1773     /* Execute the real process.  If successful, this does not return.  */
1774     execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
1775     /* TODO: What does VMS do if the child fails to start?  */
1776
1777     /* Failure.  Report error to parent and terminate.  */
1778     kwsysProcessChildErrorExit(si->ErrorPipe[1]);
1779     }
1780
1781 #if defined(__VMS)
1782   /* Restore the standard pipes of this process.  */
1783   decc$set_child_standard_streams(0, 1, 2);
1784 #endif
1785
1786   /* A child has been created.  */
1787   ++cp->CommandsLeft;
1788
1789   /* We are done with the error reporting pipe write end.  */
1790   kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
1791
1792   /* Block until the child's exec call succeeds and closes the error
1793      pipe or writes data to the pipe to report an error.  */
1794   {
1795   kwsysProcess_ssize_t total = 0;
1796   kwsysProcess_ssize_t n = 1;
1797   /* Read the entire error message up to the length of our buffer.  */
1798   while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
1799     {
1800     /* Keep trying to read until the operation is not interrupted.  */
1801     while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
1802                      (size_t)(KWSYSPE_PIPE_BUFFER_SIZE-total))) < 0) &&
1803           (errno == EINTR));
1804     if(n > 0)
1805       {
1806       total += n;
1807       }
1808     }
1809
1810   /* We are done with the error reporting pipe read end.  */
1811   kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
1812
1813   if(total > 0)
1814     {
1815     /* The child failed to execute the process.  */
1816     return 0;
1817     }
1818   }
1819
1820   /* Successfully created this child process.  */
1821   if(prIndex > 0 || si->StdIn > 0)
1822     {
1823     /* The parent process does not need the input pipe read end.  */
1824     kwsysProcessCleanupDescriptor(&si->StdIn);
1825     }
1826
1827   /* The parent process does not need the output pipe write ends.  */
1828   if(si->StdOut != 1)
1829     {
1830     kwsysProcessCleanupDescriptor(&si->StdOut);
1831     }
1832
1833   return 1;
1834 }
1835
1836 /*--------------------------------------------------------------------------*/
1837 static void kwsysProcessDestroy(kwsysProcess* cp)
1838 {
1839   /* A child process has terminated.  Reap it if it is one handled by
1840      this object.  */
1841   int i;
1842   for(i=0; i < cp->NumberOfCommands; ++i)
1843     {
1844     if(cp->ForkPIDs[i])
1845       {
1846       int result;
1847       while(((result = waitpid(cp->ForkPIDs[i],
1848                                &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
1849             (errno == EINTR));
1850       if(result > 0)
1851         {
1852         /* This child has termianted.  */
1853         cp->ForkPIDs[i] = 0;
1854         if(--cp->CommandsLeft == 0)
1855           {
1856           /* All children have terminated.  Close the signal pipe
1857              write end so that no more notifications are sent to this
1858              object.  */
1859           kwsysProcessCleanupDescriptor(&cp->SignalPipe);
1860
1861           /* TODO: Once the children have terminated, switch
1862              WaitForData to use a non-blocking read to get the
1863              rest of the data from the pipe.  This is needed when
1864              grandchildren keep the output pipes open.  */
1865           }
1866         }
1867       else if(result < 0 && cp->State != kwsysProcess_State_Error)
1868         {
1869         /* Unexpected error.  Report the first time this happens.  */
1870         strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
1871         cp->State = kwsysProcess_State_Error;
1872         }
1873       }
1874     }
1875 }
1876
1877 /*--------------------------------------------------------------------------*/
1878 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
1879 {
1880   int fout;
1881   if(!name)
1882     {
1883     return 1;
1884     }
1885
1886   /* Close the existing descriptor.  */
1887   kwsysProcessCleanupDescriptor(p);
1888
1889   /* Open a file for the pipe to write.  */
1890   if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
1891     {
1892     return 0;
1893     }
1894
1895   /* Set close-on-exec flag on the pipe's end.  */
1896   if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
1897     {
1898     return 0;
1899     }
1900
1901   /* Assign the replacement descriptor.  */
1902   *p = fout;
1903   return 1;  
1904 }
1905
1906 /*--------------------------------------------------------------------------*/
1907 static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
1908 {
1909   /* Close the existing descriptor.  */
1910   kwsysProcessCleanupDescriptor(p);
1911
1912   /* Set close-on-exec flag on the pipe's ends.  The proper end will
1913      be dup2-ed into the standard descriptor number after fork but
1914      before exec.  */
1915   if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
1916      (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
1917     {
1918     return 0;
1919     }
1920
1921   /* Assign the replacement descriptor.  */
1922   *p = des[1];
1923   return 1;
1924 }
1925
1926 /*--------------------------------------------------------------------------*/
1927 /* Get the time at which either the process or user timeout will
1928    expire.  Returns 1 if the user timeout is first, and 0 otherwise.  */
1929 static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
1930                                       kwsysProcessTime* timeoutTime)
1931 {
1932   /* The first time this is called, we need to calculate the time at
1933      which the child will timeout.  */
1934   if(cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0)
1935     {
1936     kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
1937     cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
1938     }
1939
1940   /* Start with process timeout.  */
1941   *timeoutTime = cp->TimeoutTime;
1942
1943   /* Check if the user timeout is earlier.  */
1944   if(userTimeout)
1945     {
1946     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1947     kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
1948     kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
1949                                                            userTimeoutLength);
1950     if(timeoutTime->tv_sec < 0 ||
1951        kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
1952       {
1953       *timeoutTime = userTimeoutTime;
1954       return 1;
1955       }
1956     }
1957   return 0;
1958 }
1959
1960 /*--------------------------------------------------------------------------*/
1961 /* Get the length of time before the given timeout time arrives.
1962    Returns 1 if the time has already arrived, and 0 otherwise.  */
1963 static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
1964                                       double* userTimeout,
1965                                       kwsysProcessTimeNative* timeoutLength,
1966                                       int zeroIsExpired)
1967 {
1968   if(timeoutTime->tv_sec < 0)
1969     {
1970     /* No timeout time has been requested.  */
1971     return 0;
1972     }
1973   else
1974     {
1975     /* Calculate the remaining time.  */
1976     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
1977     kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
1978                                                          currentTime);
1979     if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
1980       {
1981       /* Caller has explicitly requested a zero timeout.  */
1982       timeLeft.tv_sec = 0;
1983       timeLeft.tv_usec = 0;
1984       }
1985
1986     if(timeLeft.tv_sec < 0 ||
1987        (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired))
1988       {
1989       /* Timeout has already expired.  */
1990       return 1;
1991       }
1992     else
1993       {
1994       /* There is some time left.  */
1995       timeoutLength->tv_sec = timeLeft.tv_sec;
1996       timeoutLength->tv_usec = timeLeft.tv_usec;
1997       return 0;
1998       }
1999     }
2000 }
2001
2002 /*--------------------------------------------------------------------------*/
2003 static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
2004 {
2005   kwsysProcessTime current;
2006   kwsysProcessTimeNative current_native;
2007   gettimeofday(&current_native, 0);
2008   current.tv_sec = (long)current_native.tv_sec;
2009   current.tv_usec = (long)current_native.tv_usec;
2010   return current;
2011 }
2012
2013 /*--------------------------------------------------------------------------*/
2014 static double kwsysProcessTimeToDouble(kwsysProcessTime t)
2015 {
2016   return (double)t.tv_sec + (double)(t.tv_usec)*0.000001;
2017 }
2018
2019 /*--------------------------------------------------------------------------*/
2020 static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
2021 {
2022   kwsysProcessTime t;
2023   t.tv_sec = (long)d;
2024   t.tv_usec = (long)((d-(double)(t.tv_sec))*1000000);
2025   return t;
2026 }
2027
2028 /*--------------------------------------------------------------------------*/
2029 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
2030 {
2031   return ((in1.tv_sec < in2.tv_sec) ||
2032           ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
2033 }
2034
2035 /*--------------------------------------------------------------------------*/
2036 static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
2037 {
2038   kwsysProcessTime out;
2039   out.tv_sec = in1.tv_sec + in2.tv_sec;
2040   out.tv_usec = in1.tv_usec + in2.tv_usec;
2041   if(out.tv_usec > 1000000)
2042     {
2043     out.tv_usec -= 1000000;
2044     out.tv_sec += 1;
2045     }
2046   return out;
2047 }
2048
2049 /*--------------------------------------------------------------------------*/
2050 static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
2051 {
2052   kwsysProcessTime out;
2053   out.tv_sec = in1.tv_sec - in2.tv_sec;
2054   out.tv_usec = in1.tv_usec - in2.tv_usec;
2055   if(out.tv_usec < 0)
2056     {
2057     out.tv_usec += 1000000;
2058     out.tv_sec -= 1;
2059     }
2060   return out;
2061 }
2062
2063 /*--------------------------------------------------------------------------*/
2064 #define KWSYSPE_CASE(type, str) \
2065   cp->ExitException = kwsysProcess_Exception_##type; \
2066   strcpy(cp->ExitExceptionString, str)
2067 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
2068 {
2069   switch (sig)
2070     {
2071 #ifdef SIGSEGV
2072     case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
2073 #endif
2074 #ifdef SIGBUS
2075 # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
2076     case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
2077 # endif
2078 #endif
2079 #ifdef SIGFPE
2080     case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
2081 #endif
2082 #ifdef SIGILL
2083     case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
2084 #endif
2085 #ifdef SIGINT
2086     case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
2087 #endif
2088 #ifdef SIGABRT
2089     case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
2090 #endif
2091 #ifdef SIGKILL
2092     case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
2093 #endif
2094 #ifdef SIGTERM
2095     case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
2096 #endif
2097 #ifdef SIGHUP
2098     case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
2099 #endif
2100 #ifdef SIGQUIT
2101     case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
2102 #endif
2103 #ifdef SIGTRAP
2104     case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
2105 #endif
2106 #ifdef SIGIOT
2107 # if !defined(SIGABRT) || SIGIOT != SIGABRT
2108     case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
2109 # endif
2110 #endif
2111 #ifdef SIGUSR1
2112     case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
2113 #endif
2114 #ifdef SIGUSR2
2115     case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
2116 #endif
2117 #ifdef SIGPIPE
2118     case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
2119 #endif
2120 #ifdef SIGALRM
2121     case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
2122 #endif
2123 #ifdef SIGSTKFLT
2124     case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
2125 #endif
2126 #ifdef SIGCHLD
2127     case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
2128 #elif defined(SIGCLD)
2129     case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
2130 #endif
2131 #ifdef SIGCONT
2132     case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
2133 #endif
2134 #ifdef SIGSTOP
2135     case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
2136 #endif
2137 #ifdef SIGTSTP
2138     case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
2139 #endif
2140 #ifdef SIGTTIN
2141     case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
2142 #endif
2143 #ifdef SIGTTOU
2144     case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
2145 #endif
2146 #ifdef SIGURG
2147     case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
2148 #endif
2149 #ifdef SIGXCPU
2150     case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
2151 #endif
2152 #ifdef SIGXFSZ
2153     case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
2154 #endif
2155 #ifdef SIGVTALRM
2156     case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
2157 #endif
2158 #ifdef SIGPROF
2159     case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
2160 #endif
2161 #ifdef SIGWINCH
2162     case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
2163 #endif
2164 #ifdef SIGPOLL
2165     case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
2166 #endif
2167 #ifdef SIGIO
2168 # if !defined(SIGPOLL) || SIGIO != SIGPOLL
2169     case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
2170 # endif
2171 #endif
2172 #ifdef SIGPWR
2173     case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
2174 #endif
2175 #ifdef SIGSYS
2176     case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
2177 #endif
2178 #ifdef SIGUNUSED
2179 # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
2180     case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
2181 # endif
2182 #endif
2183     default:
2184       cp->ExitException = kwsysProcess_Exception_Other;
2185       sprintf(cp->ExitExceptionString, "Signal %d", sig);
2186       break;
2187     }
2188 }
2189 #undef KWSYSPE_CASE
2190
2191 /*--------------------------------------------------------------------------*/
2192 /* When the child process encounters an error before its program is
2193    invoked, this is called to report the error to the parent and
2194    exit.  */
2195 static void kwsysProcessChildErrorExit(int errorPipe)
2196 {
2197   /* Construct the error message.  */
2198   char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
2199   kwsysProcess_ssize_t result;
2200   strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
2201
2202   /* Report the error to the parent through the special pipe.  */
2203   result=write(errorPipe, buffer, strlen(buffer));
2204   (void)result;
2205
2206   /* Terminate without cleanup.  */
2207   _exit(1);
2208 }
2209
2210 /*--------------------------------------------------------------------------*/
2211 /* Restores all signal handlers to their default values.  */
2212 static void kwsysProcessRestoreDefaultSignalHandlers(void)
2213 {
2214   struct sigaction act;
2215   memset(&act, 0, sizeof(struct sigaction));
2216   act.sa_handler = SIG_DFL;
2217 #ifdef SIGHUP
2218   sigaction(SIGHUP, &act, 0);
2219 #endif
2220 #ifdef SIGINT
2221   sigaction(SIGINT, &act, 0);
2222 #endif
2223 #ifdef SIGQUIT
2224   sigaction(SIGQUIT, &act, 0);
2225 #endif
2226 #ifdef SIGILL
2227   sigaction(SIGILL, &act, 0);
2228 #endif
2229 #ifdef SIGTRAP
2230   sigaction(SIGTRAP, &act, 0);
2231 #endif
2232 #ifdef SIGABRT
2233   sigaction(SIGABRT, &act, 0);
2234 #endif
2235 #ifdef SIGIOT
2236   sigaction(SIGIOT, &act, 0);
2237 #endif
2238 #ifdef SIGBUS
2239   sigaction(SIGBUS, &act, 0);
2240 #endif
2241 #ifdef SIGFPE
2242   sigaction(SIGFPE, &act, 0);
2243 #endif
2244 #ifdef SIGUSR1
2245   sigaction(SIGUSR1, &act, 0);
2246 #endif
2247 #ifdef SIGSEGV
2248   sigaction(SIGSEGV, &act, 0);
2249 #endif
2250 #ifdef SIGUSR2
2251   sigaction(SIGUSR2, &act, 0);
2252 #endif
2253 #ifdef SIGPIPE
2254   sigaction(SIGPIPE, &act, 0);
2255 #endif
2256 #ifdef SIGALRM
2257   sigaction(SIGALRM, &act, 0);
2258 #endif
2259 #ifdef SIGTERM
2260   sigaction(SIGTERM, &act, 0);
2261 #endif
2262 #ifdef SIGSTKFLT
2263   sigaction(SIGSTKFLT, &act, 0);
2264 #endif
2265 #ifdef SIGCLD
2266   sigaction(SIGCLD, &act, 0);
2267 #endif
2268 #ifdef SIGCHLD
2269   sigaction(SIGCHLD, &act, 0);
2270 #endif
2271 #ifdef SIGCONT
2272   sigaction(SIGCONT, &act, 0);
2273 #endif
2274 #ifdef SIGTSTP
2275   sigaction(SIGTSTP, &act, 0);
2276 #endif
2277 #ifdef SIGTTIN
2278   sigaction(SIGTTIN, &act, 0);
2279 #endif
2280 #ifdef SIGTTOU
2281   sigaction(SIGTTOU, &act, 0);
2282 #endif
2283 #ifdef SIGURG
2284   sigaction(SIGURG, &act, 0);
2285 #endif
2286 #ifdef SIGXCPU
2287   sigaction(SIGXCPU, &act, 0);
2288 #endif
2289 #ifdef SIGXFSZ
2290   sigaction(SIGXFSZ, &act, 0);
2291 #endif
2292 #ifdef SIGVTALRM
2293   sigaction(SIGVTALRM, &act, 0);
2294 #endif
2295 #ifdef SIGPROF
2296   sigaction(SIGPROF, &act, 0);
2297 #endif
2298 #ifdef SIGWINCH
2299   sigaction(SIGWINCH, &act, 0);
2300 #endif
2301 #ifdef SIGPOLL
2302   sigaction(SIGPOLL, &act, 0);
2303 #endif
2304 #ifdef SIGIO
2305   sigaction(SIGIO, &act, 0);
2306 #endif
2307 #ifdef SIGPWR
2308   sigaction(SIGPWR, &act, 0);
2309 #endif
2310 #ifdef SIGSYS
2311   sigaction(SIGSYS, &act, 0);
2312 #endif
2313 #ifdef SIGUNUSED
2314   sigaction(SIGUNUSED, &act, 0);
2315 #endif
2316 }
2317
2318 /*--------------------------------------------------------------------------*/
2319 static void kwsysProcessExit(void)
2320 {
2321   _exit(0);
2322 }
2323
2324 /*--------------------------------------------------------------------------*/
2325 #if !defined(__VMS)
2326 static pid_t kwsysProcessFork(kwsysProcess* cp,
2327                               kwsysProcessCreateInformation* si)
2328 {
2329   /* Create a detached process if requested.  */
2330   if(cp->OptionDetach)
2331     {
2332     /* Create an intermediate process.  */
2333     pid_t middle_pid = fork();
2334     if(middle_pid < 0)
2335       {
2336       /* Fork failed.  Return as if we were not detaching.  */
2337       return middle_pid;
2338       }
2339     else if(middle_pid == 0)
2340       {
2341       /* This is the intermediate process.  Create the real child.  */
2342       pid_t child_pid = fork();
2343       if(child_pid == 0)
2344         {
2345         /* This is the real child process.  There is nothing to do here.  */
2346         return 0;
2347         }
2348       else
2349         {
2350         /* Use the error pipe to report the pid to the real parent.  */
2351         while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
2352               (errno == EINTR));
2353
2354         /* Exit without cleanup.  The parent holds all resources.  */
2355         kwsysProcessExit();
2356         return 0; /* Never reached, but avoids SunCC warning.  */
2357         }
2358       }
2359     else
2360       {
2361       /* This is the original parent process.  The intermediate
2362          process will use the error pipe to report the pid of the
2363          detached child.  */
2364       pid_t child_pid;
2365       int status;
2366       while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
2367             (errno == EINTR));
2368
2369       /* Wait for the intermediate process to exit and clean it up.  */
2370       while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
2371       return child_pid;
2372       }
2373     }
2374   else
2375     {
2376     /* Not creating a detached process.  Use normal fork.  */
2377     return fork();
2378     }
2379 }
2380 #endif
2381
2382 /*--------------------------------------------------------------------------*/
2383 /* We try to obtain process information by invoking the ps command.
2384    Here we define the command to call on each platform and the
2385    corresponding parsing format string.  The parsing format should
2386    have two integers to store: the pid and then the ppid.  */
2387 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) \
2388    || defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__)
2389 # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
2390 # define KWSYSPE_PS_FORMAT  "%d %d\n"
2391 #elif defined(__sun) && (defined(__SVR4) || defined(__svr4__)) /* Solaris */
2392 # define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid"
2393 # define KWSYSPE_PS_FORMAT  "%d %d\n"
2394 #elif defined(__hpux) || defined(__sun__) || defined(__sgi) || defined(_AIX) \
2395    || defined(__sparc)
2396 # define KWSYSPE_PS_COMMAND "ps -ef"
2397 # define KWSYSPE_PS_FORMAT  "%*s %d %d %*[^\n]\n"
2398 #elif defined(__QNX__)
2399 # define KWSYSPE_PS_COMMAND "ps -Af"
2400 # define KWSYSPE_PS_FORMAT  "%*d %d %d %*[^\n]\n"
2401 #elif defined(__CYGWIN__)
2402 # define KWSYSPE_PS_COMMAND "ps aux"
2403 # define KWSYSPE_PS_FORMAT  "%d %d %*[^\n]\n"
2404 #endif
2405
2406 /*--------------------------------------------------------------------------*/
2407 static void kwsysProcessKill(pid_t process_id)
2408 {
2409 #if defined(__linux__) || defined(__CYGWIN__)
2410   DIR* procdir;
2411 #endif
2412
2413   /* Suspend the process to be sure it will not create more children.  */
2414   kill(process_id, SIGSTOP);
2415
2416   /* Kill all children if we can find them.  */
2417 #if defined(__linux__) || defined(__CYGWIN__)
2418   /* First try using the /proc filesystem.  */
2419   if((procdir = opendir("/proc")) != NULL)
2420     {
2421 #if defined(MAXPATHLEN)
2422     char fname[MAXPATHLEN];
2423 #elif defined(PATH_MAX)
2424     char fname[PATH_MAX];
2425 #else
2426     char fname[4096];
2427 #endif
2428     char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
2429     struct dirent* d;
2430
2431     /* Each process has a directory in /proc whose name is the pid.
2432        Within this directory is a file called stat that has the
2433        following format:
2434
2435          pid (command line) status ppid ...
2436
2437        We want to get the ppid for all processes.  Those that have
2438        process_id as their parent should be recursively killed.  */
2439     for(d = readdir(procdir); d; d = readdir(procdir))
2440       {
2441       int pid;
2442       if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
2443         {
2444         struct stat finfo;
2445         sprintf(fname, "/proc/%d/stat", pid);
2446         if(stat(fname, &finfo) == 0)
2447           {
2448           FILE* f = fopen(fname, "r");
2449           if(f)
2450             {
2451             size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
2452             buffer[nread] = '\0';
2453             if(nread > 0)
2454               {
2455               const char* rparen = strrchr(buffer, ')');
2456               int ppid;
2457               if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
2458                 {
2459                 if(ppid == process_id)
2460                   {
2461                   /* Recursively kill this child and its children.  */
2462                   kwsysProcessKill(pid);
2463                   }
2464                 }
2465               }
2466             fclose(f);
2467             }
2468           }
2469         }
2470       }
2471     closedir(procdir);
2472     }
2473   else
2474 #endif
2475     {
2476 #if defined(KWSYSPE_PS_COMMAND)
2477     /* Try running "ps" to get the process information.  */
2478     FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
2479
2480     /* Make sure the process started and provided a valid header.  */
2481     if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
2482       {
2483       /* Look for processes whose parent is the process being killed.  */
2484       int pid, ppid;
2485       while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
2486         {
2487         if(ppid == process_id)
2488           {
2489           /* Recursively kill this child and its children.  */
2490           kwsysProcessKill(pid);
2491           }
2492         }
2493       }
2494
2495     /* We are done with the ps process.  */
2496     if(ps)
2497       {
2498       pclose(ps);
2499       }
2500 #endif
2501     }
2502
2503   /* Kill the process.  */
2504   kill(process_id, SIGKILL);
2505
2506 #if defined(__APPLE__)
2507   /* On OS X 10.3 the above SIGSTOP occasionally prevents the SIGKILL
2508      from working.  Just in case, we resume the child and kill it
2509      again.  There is a small race condition in this obscure case.  If
2510      the child manages to fork again between these two signals, we
2511      will not catch its children.  */
2512   kill(process_id, SIGCONT);
2513   kill(process_id, SIGKILL);
2514 #endif
2515 }
2516
2517 /*--------------------------------------------------------------------------*/
2518 #if defined(__VMS)
2519 int decc$feature_get_index(const char* name);
2520 int decc$feature_set_value(int index, int mode, int value);
2521 static int kwsysProcessSetVMSFeature(const char* name, int value)
2522 {
2523   int i;
2524   errno = 0;
2525   i = decc$feature_get_index(name);
2526   return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
2527 }
2528 #endif
2529
2530 /*--------------------------------------------------------------------------*/
2531 /* Global set of executing processes for use by the signal handler.
2532    This global instance will be zero-initialized by the compiler.  */
2533 typedef struct kwsysProcessInstances_s
2534 {
2535   int Count;
2536   int Size;
2537   kwsysProcess** Processes;
2538 } kwsysProcessInstances;
2539 static kwsysProcessInstances kwsysProcesses;
2540
2541 /* The old SIGCHLD handler.  */
2542 static struct sigaction kwsysProcessesOldSigChldAction;
2543
2544 /*--------------------------------------------------------------------------*/
2545 static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
2546 {
2547   /* Block SIGCHLD while we update the set of pipes to check.
2548      TODO: sigprocmask is undefined for threaded apps.  See
2549      pthread_sigmask.  */
2550   sigset_t newset;
2551   sigset_t oldset;
2552   sigemptyset(&newset);
2553   sigaddset(&newset, SIGCHLD);
2554   sigprocmask(SIG_BLOCK, &newset, &oldset);
2555
2556   /* Store the new set in that seen by the signal handler.  */
2557   kwsysProcesses = *newProcesses;
2558
2559   /* Restore the signal mask to the previous setting.  */
2560   sigprocmask(SIG_SETMASK, &oldset, 0);
2561 }
2562
2563 /*--------------------------------------------------------------------------*/
2564 static int kwsysProcessesAdd(kwsysProcess* cp)
2565 {
2566   /* Create a pipe through which the signal handler can notify the
2567      given process object that a child has exited.  */
2568   {
2569   /* Create the pipe.  */
2570   int p[2];
2571   if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
2572     {
2573     return 0;
2574     }
2575
2576   /* Store the pipes now to be sure they are cleaned up later.  */
2577   cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
2578   cp->SignalPipe = p[1];
2579
2580   /* Switch the pipe to non-blocking mode so that reading a byte can
2581      be an atomic test-and-set.  */
2582   if(!kwsysProcessSetNonBlocking(p[0]) ||
2583      !kwsysProcessSetNonBlocking(p[1]))
2584     {
2585     return 0;
2586     }
2587
2588   /* The children do not need this pipe.  Set close-on-exec flag on
2589      the pipe's ends.  */
2590   if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
2591      (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
2592     {
2593     return 0;
2594     }
2595   }
2596
2597   /* Attempt to add the given signal pipe to the signal handler set.  */
2598   {
2599
2600   /* Make sure there is enough space for the new signal pipe.  */
2601   kwsysProcessInstances oldProcesses = kwsysProcesses;
2602   kwsysProcessInstances newProcesses = oldProcesses;
2603   if(oldProcesses.Count == oldProcesses.Size)
2604     {
2605     /* Start with enough space for a small number of process instances
2606        and double the size each time more is needed.  */
2607     newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
2608
2609     /* Try allocating the new block of memory.  */
2610     if((newProcesses.Processes = ((kwsysProcess**)
2611                                   malloc((size_t)(newProcesses.Size)*
2612                                          sizeof(kwsysProcess*)))))
2613       {
2614       /* Copy the old pipe set to the new memory.  */
2615       if(oldProcesses.Count > 0)
2616         {
2617         memcpy(newProcesses.Processes, oldProcesses.Processes,
2618                ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
2619         }
2620       }
2621     else
2622       {
2623       /* Failed to allocate memory for the new signal pipe set.  */
2624       return 0;
2625       }
2626     }
2627
2628   /* Append the new signal pipe to the set.  */
2629   newProcesses.Processes[newProcesses.Count++] = cp;
2630
2631   /* Store the new set in that seen by the signal handler.  */
2632   kwsysProcessesUpdate(&newProcesses);
2633
2634   /* Free the original pipes if new ones were allocated.  */
2635   if(newProcesses.Processes != oldProcesses.Processes)
2636     {
2637     free(oldProcesses.Processes);
2638     }
2639
2640   /* If this is the first process, enable the signal handler.  */
2641   if(newProcesses.Count == 1)
2642     {
2643     /* Install our handler for SIGCHLD.  Repeat call until it is not
2644        interrupted.  */
2645     struct sigaction newSigChldAction;
2646     memset(&newSigChldAction, 0, sizeof(struct sigaction));
2647 #if KWSYSPE_USE_SIGINFO
2648     newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
2649     newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2650 # ifdef SA_RESTART
2651     newSigChldAction.sa_flags |= SA_RESTART;
2652 # endif
2653 #else
2654     newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2655     newSigChldAction.sa_flags = SA_NOCLDSTOP;
2656 #endif
2657     while((sigaction(SIGCHLD, &newSigChldAction,
2658                      &kwsysProcessesOldSigChldAction) < 0) &&
2659           (errno == EINTR));
2660     }
2661   }
2662
2663   return 1;
2664 }
2665
2666 /*--------------------------------------------------------------------------*/
2667 static void kwsysProcessesRemove(kwsysProcess* cp)
2668 {
2669   /* Attempt to remove the given signal pipe from the signal handler set.  */
2670   {
2671   /* Find the given process in the set.  */
2672   kwsysProcessInstances newProcesses = kwsysProcesses;
2673   int i;
2674   for(i=0; i < newProcesses.Count; ++i)
2675     {
2676     if(newProcesses.Processes[i] == cp)
2677       {
2678       break;
2679       }
2680     }
2681   if(i < newProcesses.Count)
2682     {
2683     /* Remove the process from the set.  */
2684     --newProcesses.Count;
2685     for(; i < newProcesses.Count; ++i)
2686       {
2687       newProcesses.Processes[i] = newProcesses.Processes[i+1];
2688       }
2689
2690     /* If this was the last process, disable the signal handler.  */
2691     if(newProcesses.Count == 0)
2692       {
2693       /* Restore the SIGCHLD handler.  Repeat call until it is not
2694          interrupted.  */
2695       while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
2696             (errno == EINTR));
2697
2698       /* Free the table of process pointers since it is now empty.
2699          This is safe because the signal handler has been removed.  */
2700       newProcesses.Size = 0;
2701       free(newProcesses.Processes);
2702       newProcesses.Processes = 0;
2703       }
2704
2705     /* Store the new set in that seen by the signal handler.  */
2706     kwsysProcessesUpdate(&newProcesses);
2707     }
2708   }
2709
2710   /* Close the pipe through which the signal handler may have notified
2711      the given process object that a child has exited.  */
2712   kwsysProcessCleanupDescriptor(&cp->SignalPipe);
2713 }
2714
2715 /*--------------------------------------------------------------------------*/
2716 static void kwsysProcessesSignalHandler(int signum
2717 #if KWSYSPE_USE_SIGINFO
2718                                         , siginfo_t* info, void* ucontext
2719 #endif
2720   )
2721 {
2722   (void)signum;
2723 #if KWSYSPE_USE_SIGINFO
2724   (void)info;
2725   (void)ucontext;
2726 #endif
2727
2728   /* Signal all process objects that a child has terminated.  */
2729   {
2730   int i;
2731   for(i=0; i < kwsysProcesses.Count; ++i)
2732     {
2733     /* Set the pipe in a signalled state.  */
2734     char buf = 1;
2735     kwsysProcess* cp = kwsysProcesses.Processes[i];
2736     kwsysProcess_ssize_t status=
2737       read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
2738     (void)status;
2739     status=write(cp->SignalPipe, &buf, 1);
2740     (void)status;
2741     }
2742   }
2743
2744 #if !KWSYSPE_USE_SIGINFO
2745   /* Re-Install our handler for SIGCHLD.  Repeat call until it is not
2746      interrupted.  */
2747   {
2748   struct sigaction newSigChldAction;
2749   memset(&newSigChldAction, 0, sizeof(struct sigaction));
2750   newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
2751   newSigChldAction.sa_flags = SA_NOCLDSTOP;
2752   while((sigaction(SIGCHLD, &newSigChldAction,
2753                    &kwsysProcessesOldSigChldAction) < 0) &&
2754         (errno == EINTR));
2755   }
2756 #endif
2757 }