ProcessUNIX.c 85.3 KB
Newer Older
1 2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
3 4
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Process.h)
5
#include KWSYS_HEADER(System.h)
6

7 8 9
/* Work-around CMake dependency scanning limitation.  This must
   duplicate the above list of headers.  */
#if 0
10 11
#include "Process.h.in"
#include "System.h.in"
12 13
#endif

14 15 16
/*

Implementation for UNIX
17

18 19 20 21 22 23 24 25 26
On UNIX, a child process is forked to exec the program.  Three output
pipes are read by the parent process using a select call to block
until data are ready.  Two of the pipes are stdout and stderr for the
child.  The third is a special pipe populated by a signal handler to
indicate that a child has terminated.  This is used in conjunction
with the timeout on the select call to implement a timeout for program
even when it closes stdout and stderr and at the same time avoiding
races.

27 28
*/

29 30 31 32 33 34 35 36 37 38 39
/*

TODO:

We cannot create the pipeline of processes in suspended states.  How
do we cleanup processes already started when one fails to load?  Right
now we are just killing them, which is probably not the right thing to
do.

*/

40 41 42
#if defined(__CYGWIN__)
/* Increase the file descriptor limit for select() before including
   related system headers. (Default: 64) */
43
#define FD_SETSIZE 16384
44 45
#endif

46 47 48 49 50 51
#include <assert.h>    /* assert */
#include <ctype.h>     /* isspace */
#include <dirent.h>    /* DIR, dirent */
#include <errno.h>     /* errno */
#include <fcntl.h>     /* fcntl */
#include <signal.h>    /* sigaction */
52
#include <stddef.h>    /* ptrdiff_t */
53 54 55
#include <stdio.h>     /* snprintf */
#include <stdlib.h>    /* malloc, free */
#include <string.h>    /* strdup, strerror, memset */
56
#include <sys/stat.h>  /* open mode */
57 58 59 60
#include <sys/time.h>  /* struct timeval */
#include <sys/types.h> /* pid_t, fd_set */
#include <sys/wait.h>  /* waitpid */
#include <time.h>      /* gettimeofday */
61
#include <unistd.h>    /* pipe, close, fork, execvp, select, _exit */
62

63
#if defined(__VMS)
64
#define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
65
#else
66
#define KWSYSPE_VMS_NONBLOCK
67 68
#endif

69 70 71 72 73 74 75 76 77 78 79 80
#if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
typedef ptrdiff_t kwsysProcess_ptrdiff_t;
#else
typedef int kwsysProcess_ptrdiff_t;
#endif

#if defined(KWSYS_C_HAS_SSIZE_T) && KWSYS_C_HAS_SSIZE_T
typedef ssize_t kwsysProcess_ssize_t;
#else
typedef int kwsysProcess_ssize_t;
#endif

81
#if defined(__BEOS__) && !defined(__ZETA__)
82
/* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
83
#include <be/kernel/OS.h>
84 85 86 87 88
static inline void kwsysProcess_usleep(unsigned int msec)
{
  snooze(msec);
}
#else
89
#define kwsysProcess_usleep usleep
90 91 92 93 94 95 96 97 98 99 100 101
#endif

/*
 * BeOS's select() works like WinSock: it's for networking only, and
 * doesn't work with Unix file handles...socket and file handles are
 * different namespaces (the same descriptor means different things in
 * each context!)
 *
 * So on Unix-like systems where select() is flakey, we'll set the
 * pipes' file handles to be non-blocking and just poll them directly
 * without select().
 */
102
#if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__)
103
#define KWSYSPE_USE_SELECT 1
104 105
#endif

106 107
/* Some platforms do not have siginfo on their signal handlers.  */
#if defined(SA_SIGINFO) && !defined(__BEOS__)
108
#define KWSYSPE_USE_SIGINFO 1
109 110
#endif

111
/* The number of pipes for the child's output.  The standard stdout
112 113 114 115
   and stderr pipes are the first two.  One more pipe is used to
   detect when the child process has terminated.  The third pipe is
   not given to the child process, so it cannot close it until it
   terminates.  */
116 117 118
#define KWSYSPE_PIPE_COUNT 3
#define KWSYSPE_PIPE_STDOUT 0
#define KWSYSPE_PIPE_STDERR 1
119
#define KWSYSPE_PIPE_SIGNAL 2
120 121 122 123

/* The maximum amount to read from a pipe at a time.  */
#define KWSYSPE_PIPE_BUFFER_SIZE 1024

124 125 126 127 128 129 130 131 132 133
/* Keep track of times using a signed representation.  Switch to the
   native (possibly unsigned) representation only when calling native
   functions.  */
typedef struct timeval kwsysProcessTimeNative;
typedef struct kwsysProcessTime_s kwsysProcessTime;
struct kwsysProcessTime_s
{
  long tv_sec;
  long tv_usec;
};
134

135 136
typedef struct kwsysProcessCreateInformation_s
{
137 138 139 140
  int StdIn;
  int StdOut;
  int StdErr;
  int ErrorPipe[2];
141 142
} kwsysProcessCreateInformation;

143
/*--------------------------------------------------------------------------*/
144
static void kwsysProcessVolatileFree(volatile void* p);
145
static int kwsysProcessInitialize(kwsysProcess* cp);
146 147
static void kwsysProcessCleanup(kwsysProcess* cp, int error);
static void kwsysProcessCleanupDescriptor(int* pfd);
148
static void kwsysProcessClosePipes(kwsysProcess* cp);
149
static int kwsysProcessSetNonBlocking(int fd);
150
static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
151
                              kwsysProcessCreateInformation* si);
152
static void kwsysProcessDestroy(kwsysProcess* cp);
153
static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
154
static int kwsysProcessSetupOutputPipeNative(int* p, int des[2]);
155 156 157
static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
                                      kwsysProcessTime* timeoutTime);
static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
158
                                      double* userTimeout,
159 160
                                      kwsysProcessTimeNative* timeoutLength,
                                      int zeroIsExpired);
161
static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
162 163 164
static double kwsysProcessTimeToDouble(kwsysProcessTime t);
static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
165 166 167 168
static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
                                            kwsysProcessTime in2);
static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
                                                 kwsysProcessTime in2);
169
static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
170
static void kwsysProcessChildErrorExit(int errorPipe);
171
static void kwsysProcessRestoreDefaultSignalHandlers(void);
172 173
static pid_t kwsysProcessFork(kwsysProcess* cp,
                              kwsysProcessCreateInformation* si);
174
static void kwsysProcessKill(pid_t process_id);
175
#if defined(__VMS)
176
static int kwsysProcessSetVMSFeature(const char* name, int value);
177
#endif
178 179
static int kwsysProcessesAdd(kwsysProcess* cp);
static void kwsysProcessesRemove(kwsysProcess* cp);
180
#if KWSYSPE_USE_SIGINFO
181 182
static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
                                        void* ucontext);
183 184 185
#else
static void kwsysProcessesSignalHandler(int signum);
#endif
186 187 188 189 190

/*--------------------------------------------------------------------------*/
/* Structure containing data used to implement the child's execution.  */
struct kwsysProcess_s
{
191 192
  /* The command lines to execute.  */
  char*** Commands;
193
  volatile int NumberOfCommands;
194

195 196
  /* Descriptors for the read ends of the child's output pipes and
     the signal pipe. */
197
  int PipeReadEnds[KWSYSPE_PIPE_COUNT];
198

199 200 201 202
  /* Descriptors for the child's ends of the pipes.
     Used temporarily during process creation.  */
  int PipeChildStd[3];

203 204 205
  /* Write descriptor for child termination signal pipe.  */
  int SignalPipe;

206 207 208
  /* Buffer for pipe data.  */
  char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];

209 210 211 212
  /* Process IDs returned by the calls to fork.  Everything is volatile
     because the signal handler accesses them.  You must be very careful
     when reaping PIDs or modifying this array to avoid race conditions.  */
  volatile pid_t* volatile ForkPIDs;
213

214 215
  /* Flag for whether the children were terminated by a faild select.  */
  int SelectError;
216

217
  /* The timeout length.  */
218
  double Timeout;
219 220 221

  /* The working directory for the process. */
  char* WorkingDirectory;
222

223 224 225 226 227 228
  /* Whether to create the child as a detached process.  */
  int OptionDetach;

  /* Whether the child was created as a detached process.  */
  int Detached;

229 230 231
  /* Whether to treat command lines as verbatim.  */
  int Verbatim;

232 233 234
  /* Whether to merge stdout/stderr of the child.  */
  int MergeOutput;

235 236 237
  /* Whether to create the process in a new process group.  */
  volatile sig_atomic_t CreateProcessGroup;

238 239
  /* Time at which the child started.  Negative for no timeout.  */
  kwsysProcessTime StartTime;
240

241 242
  /* Time at which the child will timeout.  Negative for no timeout.  */
  kwsysProcessTime TimeoutTime;
243

244 245
  /* Flag for whether the timeout expired.  */
  int TimeoutExpired;
246

247 248
  /* The number of pipes left open during execution.  */
  int PipesLeft;
249

250
#if KWSYSPE_USE_SELECT
251 252
  /* File descriptor set for call to select.  */
  fd_set PipeSet;
253
#endif
254

255 256 257
  /* The number of children still executing.  */
  int CommandsLeft;

258 259 260
  /* The current status of the child process.  Must be atomic because
     the signal handler checks this to avoid a race.  */
  volatile sig_atomic_t State;
261

262 263 264
  /* The exceptional behavior that terminated the child process, if
   * any.  */
  int ExitException;
265

266
  /* The exit code of the child process.  */
267
  int ExitCode;
268

269 270
  /* The exit value of the child process, if any.  */
  int ExitValue;
271

272
  /* Whether the process was killed.  */
273
  volatile sig_atomic_t Killed;
274

275
  /* Buffer for error message in case of failure.  */
276
  char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1];
277

278
  /* Description for the ExitException.  */
279
  char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1];
280

281 282
  /* The exit codes of each child process in the pipeline.  */
  int* CommandExitCodes;
283 284 285 286 287 288

  /* Name of files to which stdin and stdout pipes are attached.  */
  char* PipeFileSTDIN;
  char* PipeFileSTDOUT;
  char* PipeFileSTDERR;

289 290 291 292 293
  /* Whether each pipe is shared with the parent process.  */
  int PipeSharedSTDIN;
  int PipeSharedSTDOUT;
  int PipeSharedSTDERR;

294 295 296 297 298
  /* Native pipes provided by the user.  */
  int PipeNativeSTDIN[2];
  int PipeNativeSTDOUT[2];
  int PipeNativeSTDERR[2];

299 300 301
  /* The real working directory of this process.  */
  int RealWorkingDirectoryLength;
  char* RealWorkingDirectory;
302 303 304
};

/*--------------------------------------------------------------------------*/
305
kwsysProcess* kwsysProcess_New(void)
306 307 308
{
  /* Allocate a process control structure.  */
  kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
309
  if (!cp) {
310
    return 0;
311
  }
312
  memset(cp, 0, sizeof(kwsysProcess));
313 314 315 316

  /* Share stdin with the parent process by default.  */
  cp->PipeSharedSTDIN = 1;

317 318 319 320 321 322 323 324
  /* No native pipes by default.  */
  cp->PipeNativeSTDIN[0] = -1;
  cp->PipeNativeSTDIN[1] = -1;
  cp->PipeNativeSTDOUT[0] = -1;
  cp->PipeNativeSTDOUT[1] = -1;
  cp->PipeNativeSTDERR[0] = -1;
  cp->PipeNativeSTDERR[1] = -1;

325
  /* Set initial status.  */
326
  cp->State = kwsysProcess_State_Starting;
327

328 329 330 331 332 333
  return cp;
}

/*--------------------------------------------------------------------------*/
void kwsysProcess_Delete(kwsysProcess* cp)
{
334
  /* Make sure we have an instance.  */
335
  if (!cp) {
336
    return;
337
  }
338

339
  /* If the process is executing, wait for it to finish.  */
340 341
  if (cp->State == kwsysProcess_State_Executing) {
    if (cp->Detached) {
342
      kwsysProcess_Disown(cp);
343
    } else {
344
      kwsysProcess_WaitForExit(cp, 0);
345
    }
346
  }
347

348 349
  /* Free memory.  */
  kwsysProcess_SetCommand(cp, 0);
350
  kwsysProcess_SetWorkingDirectory(cp, 0);
351 352 353
  kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
  kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
  kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
354
  if (cp->CommandExitCodes) {
355
    free(cp->CommandExitCodes);
356
  }
357 358 359 360
  free(cp);
}

/*--------------------------------------------------------------------------*/
361
int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
362
{
363
  int i;
364
  if (!cp) {
365
    return 0;
366 367
  }
  for (i = 0; i < cp->NumberOfCommands; ++i) {
368
    char** c = cp->Commands[i];
369
    while (*c) {
370
      free(*c++);
371
    }
372 373
    free(cp->Commands[i]);
  }
374
  cp->NumberOfCommands = 0;
375
  if (cp->Commands) {
376 377
    free(cp->Commands);
    cp->Commands = 0;
378 379
  }
  if (command) {
380
    return kwsysProcess_AddCommand(cp, command);
381
  }
382 383 384 385 386 387 388 389 390 391
  return 1;
}

/*--------------------------------------------------------------------------*/
int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
{
  int newNumberOfCommands;
  char*** newCommands;

  /* Make sure we have a command to add.  */
392
  if (!cp || !command || !*command) {
393
    return 0;
394
  }
395 396 397

  /* Allocate a new array for command pointers.  */
  newNumberOfCommands = cp->NumberOfCommands + 1;
398 399
  if (!(newCommands =
          (char***)malloc(sizeof(char**) * (size_t)(newNumberOfCommands)))) {
400 401
    /* Out of memory.  */
    return 0;
402
  }
403 404 405

  /* Copy any existing commands into the new array.  */
  {
406 407 408
    int i;
    for (i = 0; i < cp->NumberOfCommands; ++i) {
      newCommands[i] = cp->Commands[i];
409 410 411 412
    }
  }

  /* Add the new command.  */
413
  if (cp->Verbatim) {
414 415 416
    /* In order to run the given command line verbatim we need to
       parse it.  */
    newCommands[cp->NumberOfCommands] =
417
      kwsysSystem_Parse_CommandForUnix(*command, 0);
418 419
    if (!newCommands[cp->NumberOfCommands] ||
        !newCommands[cp->NumberOfCommands][0]) {
420
      /* Out of memory or no command parsed.  */
421 422
      free(newCommands);
      return 0;
423
    }
424
  } else {
425 426
    /* Copy each argument string individually.  */
    char const* const* c = command;
427 428
    kwsysProcess_ptrdiff_t n = 0;
    kwsysProcess_ptrdiff_t i = 0;
429 430
    while (*c++)
      ;
431
    n = c - command - 1;
Francois Bertel's avatar
Francois Bertel committed
432
    newCommands[cp->NumberOfCommands] =
433 434
      (char**)malloc((size_t)(n + 1) * sizeof(char*));
    if (!newCommands[cp->NumberOfCommands]) {
435 436 437
      /* Out of memory.  */
      free(newCommands);
      return 0;
438 439
    }
    for (i = 0; i < n; ++i) {
440
      assert(command[i]); /* Quiet Clang scan-build. */
441
      newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
442
      if (!newCommands[cp->NumberOfCommands][i]) {
443 444
        break;
      }
445 446
    }
    if (i < n) {
447
      /* Out of memory.  */
448 449 450
      for (; i > 0; --i) {
        free(newCommands[cp->NumberOfCommands][i - 1]);
      }
451 452
      free(newCommands);
      return 0;
453
    }
454 455
    newCommands[cp->NumberOfCommands][n] = 0;
  }
456 457 458 459 460 461 462

  /* Successfully allocated new command array.  Free the old array. */
  free(cp->Commands);
  cp->Commands = newCommands;
  cp->NumberOfCommands = newNumberOfCommands;

  return 1;
463 464 465 466 467
}

/*--------------------------------------------------------------------------*/
void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
{
468
  if (!cp) {
469
    return;
470
  }
471
  cp->Timeout = timeout;
472
  if (cp->Timeout < 0) {
473
    cp->Timeout = 0;
474
  }
475 476
  // Force recomputation of TimeoutTime.
  cp->TimeoutTime.tv_sec = -1;
477 478 479
}

/*--------------------------------------------------------------------------*/
480
int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
481
{
482
  if (!cp) {
483
    return 0;
484 485
  }
  if (cp->WorkingDirectory == dir) {
486
    return 1;
487 488
  }
  if (cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0) {
489
    return 1;
490 491
  }
  if (cp->WorkingDirectory) {
492 493
    free(cp->WorkingDirectory);
    cp->WorkingDirectory = 0;
494 495
  }
  if (dir) {
496
    cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
497
    if (!cp->WorkingDirectory) {
498
      return 0;
499
    }
500 501
    strcpy(cp->WorkingDirectory, dir);
  }
502 503 504 505
  return 1;
}

/*--------------------------------------------------------------------------*/
506
int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
507 508
{
  char** pfile;
509
  if (!cp) {
510
    return 0;
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
  }
  switch (prPipe) {
    case kwsysProcess_Pipe_STDIN:
      pfile = &cp->PipeFileSTDIN;
      break;
    case kwsysProcess_Pipe_STDOUT:
      pfile = &cp->PipeFileSTDOUT;
      break;
    case kwsysProcess_Pipe_STDERR:
      pfile = &cp->PipeFileSTDERR;
      break;
    default:
      return 0;
  }
  if (*pfile) {
526 527
    free(*pfile);
    *pfile = 0;
528 529 530 531
  }
  if (file) {
    *pfile = (char*)malloc(strlen(file) + 1);
    if (!*pfile) {
532 533
      return 0;
    }
534 535
    strcpy(*pfile, file);
  }
536

537 538
  /* If we are redirecting the pipe, do not share it or use a native
     pipe.  */
539
  if (*pfile) {
540
    kwsysProcess_SetPipeNative(cp, prPipe, 0);
541
    kwsysProcess_SetPipeShared(cp, prPipe, 0);
542
  }
543
  return 1;
544 545
}

546
/*--------------------------------------------------------------------------*/
547
void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
548
{
549
  if (!cp) {
550
    return;
551
  }
552

553 554 555 556 557 558 559 560 561 562 563 564 565
  switch (prPipe) {
    case kwsysProcess_Pipe_STDIN:
      cp->PipeSharedSTDIN = shared ? 1 : 0;
      break;
    case kwsysProcess_Pipe_STDOUT:
      cp->PipeSharedSTDOUT = shared ? 1 : 0;
      break;
    case kwsysProcess_Pipe_STDERR:
      cp->PipeSharedSTDERR = shared ? 1 : 0;
      break;
    default:
      return;
  }
566

567 568
  /* If we are sharing the pipe, do not redirect it to a file or use a
     native pipe.  */
569
  if (shared) {
570
    kwsysProcess_SetPipeFile(cp, prPipe, 0);
571
    kwsysProcess_SetPipeNative(cp, prPipe, 0);
572
  }
573 574 575 576 577 578 579
}

/*--------------------------------------------------------------------------*/
void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
{
  int* pPipeNative = 0;

580
  if (!cp) {
581
    return;
582
  }
583

584 585 586 587 588 589 590 591 592 593 594 595 596
  switch (prPipe) {
    case kwsysProcess_Pipe_STDIN:
      pPipeNative = cp->PipeNativeSTDIN;
      break;
    case kwsysProcess_Pipe_STDOUT:
      pPipeNative = cp->PipeNativeSTDOUT;
      break;
    case kwsysProcess_Pipe_STDERR:
      pPipeNative = cp->PipeNativeSTDERR;
      break;
    default:
      return;
  }
597 598

  /* Copy the native pipe descriptors provided.  */
599
  if (p) {
600 601
    pPipeNative[0] = p[0];
    pPipeNative[1] = p[1];
602
  } else {
603 604
    pPipeNative[0] = -1;
    pPipeNative[1] = -1;
605
  }
606 607 608

  /* If we are using a native pipe, do not share it or redirect it to
     a file.  */
609
  if (p) {
610 611
    kwsysProcess_SetPipeFile(cp, prPipe, 0);
    kwsysProcess_SetPipeShared(cp, prPipe, 0);
612
  }
613 614
}

615 616 617
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
{
618
  if (!cp) {
619
    return 0;
620
  }
621

622 623 624 625 626 627 628
  switch (optionId) {
    case kwsysProcess_Option_Detach:
      return cp->OptionDetach;
    case kwsysProcess_Option_MergeOutput:
      return cp->MergeOutput;
    case kwsysProcess_Option_Verbatim:
      return cp->Verbatim;
629 630
    case kwsysProcess_Option_CreateProcessGroup:
      return cp->CreateProcessGroup;
631 632 633
    default:
      return 0;
  }
634 635 636 637 638
}

/*--------------------------------------------------------------------------*/
void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
{
639
  if (!cp) {
640
    return;
641
  }
642

643 644 645 646 647 648 649 650 651 652
  switch (optionId) {
    case kwsysProcess_Option_Detach:
      cp->OptionDetach = value;
      break;
    case kwsysProcess_Option_MergeOutput:
      cp->MergeOutput = value;
      break;
    case kwsysProcess_Option_Verbatim:
      cp->Verbatim = value;
      break;
653
    case kwsysProcess_Option_CreateProcessGroup:
654 655 656 657 658
      cp->CreateProcessGroup = value;
      break;
    default:
      break;
  }
659 660
}

661
/*--------------------------------------------------------------------------*/
662 663
int kwsysProcess_GetState(kwsysProcess* cp)
{
664
  return cp ? cp->State : kwsysProcess_State_Error;
665 666
}

667 668 669
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitException(kwsysProcess* cp)
{
670
  return cp ? cp->ExitException : kwsysProcess_Exception_Other;
671 672
}

673 674 675
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitCode(kwsysProcess* cp)
{
676
  return cp ? cp->ExitCode : 0;
677 678
}

679 680 681
/*--------------------------------------------------------------------------*/
int kwsysProcess_GetExitValue(kwsysProcess* cp)
{
682
  return cp ? cp->ExitValue : -1;
683 684
}

685 686 687
/*--------------------------------------------------------------------------*/
const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
{
688
  if (!cp) {
689
    return "Process management structure could not be allocated";
690
  } else if (cp->State == kwsysProcess_State_Error) {
691
    return cp->ErrorMessage;
692
  }
693 694 695 696 697 698
  return "Success";
}

/*--------------------------------------------------------------------------*/
const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
{
699
  if (!cp) {
700
    return "GetExceptionString called with NULL process management structure";
701
  } else if (cp->State == kwsysProcess_State_Exception) {
702
    return cp->ExitExceptionString;
703
  }
704
  return "No exception";
705 706 707 708 709 710
}

/*--------------------------------------------------------------------------*/
void kwsysProcess_Execute(kwsysProcess* cp)
{
  int i;
711

712
  /* Do not execute a second copy simultaneously.  */
713
  if (!cp || cp->State == kwsysProcess_State_Executing) {
714
    return;
715
  }
716

717
  /* Make sure we have something to run.  */
718
  if (cp->NumberOfCommands < 1) {
719 720 721
    strcpy(cp->ErrorMessage, "No command");
    cp->State = kwsysProcess_State_Error;
    return;
722
  }
723

724
  /* Initialize the control structure for a new process.  */
725
  if (!kwsysProcessInitialize(cp)) {
726 727 728
    strcpy(cp->ErrorMessage, "Out of memory");
    cp->State = kwsysProcess_State_Error;
    return;
729
  }
730

731
#if defined(__VMS)
732
  /* Make sure pipes behave like streams on VMS.  */
733
  if (!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1)) {
734 735
    kwsysProcessCleanup(cp, 1);
    return;
736
  }
737
#endif
738

739 740 741
  /* Save the real working directory of this process and change to
     the working directory for the child processes.  This is needed
     to make pipe file paths evaluate correctly.  */
742
  if (cp->WorkingDirectory) {
743
    int r;
744 745
    if (!getcwd(cp->RealWorkingDirectory,
                (size_t)(cp->RealWorkingDirectoryLength))) {
746 747
      kwsysProcessCleanup(cp, 1);
      return;
748
    }
749 750 751

    /* Some platforms specify that the chdir call may be
       interrupted.  Repeat the call until it finishes.  */
752 753 754
    while (((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR))
      ;
    if (r < 0) {
755
      kwsysProcessCleanup(cp, 1);
756
      return;
757
    }
758
  }
759

760 761 762
  /* If not running a detached child, add this object to the global
     set of process objects that wish to be notified when a child
     exits.  */
763 764
  if (!cp->OptionDetach) {
    if (!kwsysProcessesAdd(cp)) {
765 766
      kwsysProcessCleanup(cp, 1);
      return;
767
    }
768
  }
769

770
  /* Setup the stdin pipe for the first process.  */
771
  if (cp->PipeFileSTDIN) {
772 773
    /* Open a file for the child's stdin to read.  */
    cp->PipeChildStd[0] = open(cp->PipeFileSTDIN, O_RDONLY);
774
    if (cp->PipeChildStd[0] < 0) {
775 776
      kwsysProcessCleanup(cp, 1);
      return;
777
    }
778 779

    /* Set close-on-exec flag on the pipe's end.  */
780
    if (fcntl(cp->PipeChildStd[0], F_SETFD, FD_CLOEXEC) < 0) {
781 782 783
      kwsysProcessCleanup(cp, 1);
      return;
    }
784
  } else if (cp->PipeSharedSTDIN) {
785
    cp->PipeChildStd[0] = 0;
786
  } else if (cp->PipeNativeSTDIN[0] >= 0) {
787 788 789 790 791
    cp->PipeChildStd[0] = cp->PipeNativeSTDIN[0];

    /* Set close-on-exec flag on the pipe's ends.  The read end will
       be dup2-ed into the stdin descriptor after the fork but before
       the exec.  */
792 793
    if ((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
        (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0)) {
794 795 796
      kwsysProcessCleanup(cp, 1);
      return;
    }
797
  } else {
798
    cp->PipeChildStd[0] = -1;
799
  }
800 801 802 803

  /* Create the output pipe for the last process.
     We always create this so the pipe can be passed to select even if
     it will report closed immediately.  */
804
  {
805 806 807 808 809
    /* Create the pipe.  */
    int p[2];
    if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
      kwsysProcessCleanup(cp, 1);
      return;
810
    }
811

812 813 814
    /* Store the pipe.  */
    cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = p[0];
    cp->PipeChildStd[1] = p[1];
815

816 817 818 819 820
    /* Set close-on-exec flag on the pipe's ends.  */
    if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
        (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
      kwsysProcessCleanup(cp, 1);
      return;
821
    }
822

823 824 825 826 827
    /* Set to non-blocking in case select lies, or for the polling
       implementation.  */
    if (!kwsysProcessSetNonBlocking(p[0])) {
      kwsysProcessCleanup(cp, 1);
      return;
828
    }
829
  }
830

831
  if (cp->PipeFileSTDOUT) {
832
    /* Use a file for stdout.  */
833 834
    if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
                                         cp->PipeFileSTDOUT)) {
835 836 837
      kwsysProcessCleanup(cp, 1);
      return;
    }
838
  } else if (cp->PipeSharedSTDOUT) {
839 840 841
    /* Use the parent stdout.  */
    kwsysProcessCleanupDescriptor(&cp->PipeChildStd[1]);
    cp->PipeChildStd[1] = 1;
842
  } else if (cp->PipeNativeSTDOUT[1] >= 0) {
843
    /* Use the given descriptor for stdout.  */
844 845
    if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[1],
                                           cp->PipeNativeSTDOUT)) {
846 847 848
      kwsysProcessCleanup(cp, 1);
      return;
    }
849
  }
850

851 852 853 854
  /* Create stderr pipe to be shared by all processes in the pipeline.
     We always create this so the pipe can be passed to select even if
     it will report closed immediately.  */
  {
855 856 857 858 859
    /* Create the pipe.  */
    int p[2];
    if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
      kwsysProcessCleanup(cp, 1);
      return;
860 861
    }

862 863 864
    /* Store the pipe.  */
    cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
    cp->PipeChildStd[2] = p[1];
865

866 867 868 869 870
    /* Set close-on-exec flag on the pipe's ends.  */
    if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
        (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
      kwsysProcessCleanup(cp, 1);
      return;
871 872
    }

873 874 875 876 877
    /* Set to non-blocking in case select lies, or for the polling
       implementation.  */
    if (!kwsysProcessSetNonBlocking(p[0])) {
      kwsysProcessCleanup(cp, 1);
      return;
878
    }
879
  }
880

881
  if (cp->PipeFileSTDERR) {
882
    /* Use a file for stderr.  */
883 884
    if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
                                         cp->PipeFileSTDERR)) {
885 886 887
      kwsysProcessCleanup(cp, 1);
      return;
    }
888
  } else if (cp->PipeSharedSTDERR) {
889 890 891
    /* Use the parent stderr.  */
    kwsysProcessCleanupDescriptor(&cp->PipeChildStd[2]);
    cp->PipeChildStd[2] = 2;
892
  } else if (cp->PipeNativeSTDERR[1] >= 0) {
893
    /* Use the given handle for stderr.  */
894 895
    if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[2],
                                           cp->PipeNativeSTDERR)) {
896 897 898
      kwsysProcessCleanup(cp, 1);
      return;
    }
899
  }
900

901 902 903 904
  /* The timeout period starts now.  */
  cp->StartTime = kwsysProcessTimeGetCurrent();
  cp->TimeoutTime.tv_sec = -1;
  cp->TimeoutTime.tv_usec = -1;
905

906 907
  /* Create the pipeline of processes.  */
  {
908 909 910 911 912 913 914 915 916 917 918 919 920 921
    kwsysProcessCreateInformation si = { -1, -1, -1, { -1, -1 } };
    int nextStdIn = cp->PipeChildStd[0];
    for (i = 0; i < cp->NumberOfCommands; ++i) {
      /* Setup the process's pipes.  */
      si.StdIn = nextStdIn;
      if (i == cp->NumberOfCommands - 1) {
        nextStdIn = -1;
        si.StdOut = cp->PipeChildStd[1];
      } else {
        /* Create a pipe to sit between the children.  */
        int p[2] = { -1, -1 };
        if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
          if (nextStdIn != cp->PipeChildStd[0]) {
            kwsysProcessCleanupDescriptor(&nextStdIn);
922
          }
923 924
          kwsysProcessCleanup(cp, 1);
          return;
925
        }
926

927 928 929 930 931 932 933
        /* Set close-on-exec flag on the pipe's ends.  */
        if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
            (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
          close(p[0]);
          close(p[1]);
          if (nextStdIn != cp->PipeChildStd[0]) {
            kwsysProcessCleanupDescriptor(&nextStdIn);
934
          }
935 936
          kwsysProcessCleanup(cp, 1);
          return;
937
        }
938 939
        nextStdIn = p[0];
        si.StdOut = p[1];
940
      }
941
      si.StdErr = cp->MergeOutput ? cp->PipeChildStd[1] : cp->PipeChildStd[2];
942 943

      {
944
        int res = kwsysProcessCreate(cp, i, &si);
945

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
        /* Close our copies of pipes used between children.  */
        if (si.StdIn != cp->PipeChildStd[0]) {
          kwsysProcessCleanupDescriptor(&si.StdIn);
        }
        if (si.StdOut != cp->PipeChildStd[1]) {
          kwsysProcessCleanupDescriptor(&si.StdOut);
        }
        if (si.StdErr != cp->PipeChildStd[2] && !cp->MergeOutput) {
          kwsysProcessCleanupDescriptor(&si.StdErr);
        }

        if (!res) {
          kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
          kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
          if (nextStdIn != cp->PipeChildStd[0]) {
            kwsysProcessCleanupDescriptor(&nextStdIn);
          }
          kwsysProcessCleanup(cp, 1);
          return;
965
        }
966
      }
967
    }
968
  }
969

970
  /* The parent process does not need the child's pipe ends.  */
971
  for (i = 0; i < 3; ++i) {
972
    kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
973
  }
974

975
  /* Restore the working directory. */
976
  if (cp->RealWorkingDirectory) {
977 978
    /* Some platforms specify that the chdir call may be
       interrupted.  Repeat the call until it finishes.  */
979 980
    while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
      ;
981 982
    free(cp->RealWorkingDirectory);
    cp->RealWorkingDirectory = 0;
983
  }
984

985 986
  /* All the pipes are now open.  */
  cp->PipesLeft = KWSYSPE_PIPE_COUNT;