Debian Codegraph @

Utilities/KWSys/ProcessUNIX.c

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