ProcessUNIX.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. /*=========================================================================
  2. Program: KWSys - Kitware System Library
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #define KWSYS_IN_PROCESS_C
  14. #include <Process.h>
  15. /*
  16. Implementation for UNIX
  17. On UNIX, a child process is forked to exec the program. Three
  18. output pipes from the child are read by the parent process using a
  19. select call to block until data are ready. Two of the pipes are
  20. stdout and stderr for the child. The third is a special error pipe
  21. that has two purposes. First, if the child cannot exec the program,
  22. the error is reported through the error pipe. Second, the error
  23. pipe is left open until the child exits. This is used in
  24. conjunction with the timeout on the select call to implement a
  25. timeout for program even when it closes stdout and stderr.
  26. */
  27. #include <stdio.h> /* snprintf */
  28. #include <stdlib.h> /* malloc, free */
  29. #include <string.h> /* strdup, strerror, memset */
  30. #include <sys/time.h> /* struct timeval */
  31. #include <sys/types.h> /* pid_t, fd_set */
  32. #include <sys/wait.h> /* waitpid */
  33. #include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
  34. #include <fcntl.h> /* fcntl */
  35. #include <errno.h> /* errno */
  36. #include <time.h> /* gettimeofday */
  37. #include <signal.h> /* sigaction */
  38. /* The number of pipes for the child's output. The standard stdout
  39. and stderr pipes are the first two. One more pipe is used for the
  40. child to report errors to the parent before the real process is
  41. invoked. */
  42. #define KWSYSPE_PIPE_COUNT 3
  43. #define KWSYSPE_PIPE_STDOUT 0
  44. #define KWSYSPE_PIPE_STDERR 1
  45. #define KWSYSPE_PIPE_ERROR 2
  46. /* The maximum amount to read from a pipe at a time. */
  47. #define KWSYSPE_PIPE_BUFFER_SIZE 1024
  48. typedef struct timeval kwsysProcessTime;
  49. /*--------------------------------------------------------------------------*/
  50. static void kwsysProcessInitialize(kwsysProcess* cp);
  51. static void kwsysProcessCleanup(kwsysProcess* cp, int error);
  52. static void kwsysProcessCleanupDescriptor(int* pfd);
  53. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  54. kwsysProcessTime* timeoutTime);
  55. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  56. kwsysProcessTime* timeoutLength);
  57. static kwsysProcessTime kwsysProcessTimeGetCurrent();
  58. static double kwsysProcessTimeToDouble(kwsysProcessTime t);
  59. static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
  60. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
  61. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
  62. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
  63. static void kwsysProcessChildErrorExit(kwsysProcess* cp);
  64. static void kwsysProcessRestoreDefaultSignalHandlers();
  65. /*--------------------------------------------------------------------------*/
  66. /* Structure containing data used to implement the child's execution. */
  67. struct kwsysProcess_s
  68. {
  69. /* The command line to execute. */
  70. char** Command;
  71. /* Descriptors for the read ends of the child's output pipes. */
  72. int PipeReadEnds[KWSYSPE_PIPE_COUNT];
  73. /* Descriptors for the write ends of the child's output pipes. */
  74. int PipeWriteEnds[KWSYSPE_PIPE_COUNT];
  75. /* Buffer for pipe data. */
  76. char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
  77. /* Process ID returned by the fork. */
  78. pid_t ForkPID;
  79. /* Flag for whether the child reported an error. */
  80. int ChildError;
  81. /* The timeout length. */
  82. double Timeout;
  83. /* Time at which the child started. Negative for no timeout. */
  84. kwsysProcessTime StartTime;
  85. /* Time at which the child will timeout. Negative for no timeout. */
  86. kwsysProcessTime TimeoutTime;
  87. /* Flag for whether the timeout expired. */
  88. int TimeoutExpired;
  89. /* The old SIGCHLD handler. */
  90. struct sigaction OldSigChldAction;
  91. /* The number of pipes left open during execution. */
  92. int PipesLeft;
  93. /* File descriptor set for call to select. */
  94. fd_set PipeSet;
  95. /* The current status of the child process. */
  96. int State;
  97. /* The exceptional behavior that terminated the child process, if
  98. * any. */
  99. int ExitException;
  100. /* The exit code of the child process. */
  101. int ExitCode;
  102. /* The exit value of the child process, if any. */
  103. int ExitValue;
  104. /* Whether the process was killed. */
  105. int Killed;
  106. /* Buffer for error message in case of failure. */
  107. char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
  108. int ErrorMessageLength;
  109. };
  110. /*--------------------------------------------------------------------------*/
  111. kwsysProcess* kwsysProcess_New()
  112. {
  113. /* Allocate a process control structure. */
  114. kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
  115. if(!cp)
  116. {
  117. return 0;
  118. }
  119. memset(cp, 0, sizeof(kwsysProcess));
  120. cp->State = kwsysProcess_State_Starting;
  121. return cp;
  122. }
  123. /*--------------------------------------------------------------------------*/
  124. void kwsysProcess_Delete(kwsysProcess* cp)
  125. {
  126. /* If the process is executing, wait for it to finish. */
  127. if(cp->State == kwsysProcess_State_Executing)
  128. {
  129. kwsysProcess_WaitForExit(cp, 0);
  130. }
  131. /* Free memory. */
  132. kwsysProcess_SetCommand(cp, 0);
  133. free(cp);
  134. }
  135. /*--------------------------------------------------------------------------*/
  136. void kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
  137. {
  138. if(cp->Command)
  139. {
  140. char** c = cp->Command;
  141. while(*c)
  142. {
  143. free(*c++);
  144. }
  145. free(cp->Command);
  146. cp->Command = 0;
  147. }
  148. if(command)
  149. {
  150. char const* const* c = command;
  151. int n = 0;
  152. int i = 0;
  153. while(*c++);
  154. n = c - command - 1;
  155. cp->Command = (char**)malloc((n+1)*sizeof(char*));
  156. for(i=0; i < n; ++i)
  157. {
  158. cp->Command[i] = strdup(command[i]);
  159. }
  160. cp->Command[n] = 0;
  161. }
  162. }
  163. /*--------------------------------------------------------------------------*/
  164. void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
  165. {
  166. cp->Timeout = timeout;
  167. if(cp->Timeout < 0)
  168. {
  169. cp->Timeout = 0;
  170. }
  171. }
  172. /*--------------------------------------------------------------------------*/
  173. int kwsysProcess_GetState(kwsysProcess* cp)
  174. {
  175. return cp->State;
  176. }
  177. /*--------------------------------------------------------------------------*/
  178. int kwsysProcess_GetExitException(kwsysProcess* cp)
  179. {
  180. return cp->ExitException;
  181. }
  182. /*--------------------------------------------------------------------------*/
  183. int kwsysProcess_GetExitCode(kwsysProcess* cp)
  184. {
  185. return cp->ExitCode;
  186. }
  187. /*--------------------------------------------------------------------------*/
  188. int kwsysProcess_GetExitValue(kwsysProcess* cp)
  189. {
  190. return cp->ExitValue;
  191. }
  192. /*--------------------------------------------------------------------------*/
  193. const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
  194. {
  195. if(cp->State == kwsysProcess_State_Error)
  196. {
  197. return cp->PipeBuffer;
  198. }
  199. return 0;
  200. }
  201. /*--------------------------------------------------------------------------*/
  202. void kwsysProcess_Execute(kwsysProcess* cp)
  203. {
  204. int i;
  205. struct sigaction newSigChldAction;
  206. /* Do not execute a second copy simultaneously. */
  207. if(cp->State == kwsysProcess_State_Executing)
  208. {
  209. return;
  210. }
  211. /* Initialize the control structure for a new process. */
  212. kwsysProcessInitialize(cp);
  213. /* We want no special handling of SIGCHLD. Repeat call until it is
  214. not interrupted. */
  215. newSigChldAction.sa_handler = SIG_DFL;
  216. while((sigaction(SIGCHLD, &newSigChldAction, &cp->OldSigChldAction) < 0) &&
  217. (errno == EINTR));
  218. /* Create pipes for subprocess output. */
  219. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  220. {
  221. int p[2];
  222. /* Create the pipe. */
  223. if(pipe(p) < 0)
  224. {
  225. kwsysProcessCleanup(cp, 1);
  226. return;
  227. }
  228. /* Set close-on-exec flag on the pipe's ends. */
  229. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  230. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  231. {
  232. kwsysProcessCleanup(cp, 1);
  233. return;
  234. }
  235. /* Store the pipe. */
  236. cp->PipeReadEnds[i] = p[0];
  237. cp->PipeWriteEnds[i] = p[1];
  238. }
  239. /* The timeout period starts now. */
  240. cp->StartTime = kwsysProcessTimeGetCurrent();
  241. cp->TimeoutTime.tv_sec = -1;
  242. cp->TimeoutTime.tv_usec = -1;
  243. /* Fork off a child process. */
  244. cp->ForkPID = fork();
  245. if(cp->ForkPID < 0)
  246. {
  247. kwsysProcessCleanup(cp, 1);
  248. return;
  249. }
  250. /* If this is the child process, run the real process. */
  251. if(cp->ForkPID == 0)
  252. {
  253. /* Close stdin. */
  254. close(0);
  255. /* Setup the stdout/stderr pipes. */
  256. dup2(cp->PipeWriteEnds[KWSYSPE_PIPE_STDOUT], 1);
  257. dup2(cp->PipeWriteEnds[KWSYSPE_PIPE_STDERR], 2);
  258. /* Clear the close-on-exec flag for stdout, stderr, and the child
  259. error report pipe. All other pipe handles will be closed when
  260. exec succeeds. */
  261. fcntl(1, F_SETFD, 0);
  262. fcntl(2, F_SETFD, 0);
  263. fcntl(cp->PipeWriteEnds[KWSYSPE_PIPE_ERROR], F_SETFD, 0);
  264. /* Restore all default signal handlers. */
  265. kwsysProcessRestoreDefaultSignalHandlers();
  266. /* Execute the real process. If successful, this does not return. */
  267. execvp(cp->Command[0], cp->Command);
  268. /* Failure. Report error to parent and terminate. */
  269. kwsysProcessChildErrorExit(cp);
  270. }
  271. /* The parent process does not need the pipe write ends. */
  272. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  273. {
  274. kwsysProcessCleanupDescriptor(&cp->PipeWriteEnds[i]);
  275. }
  276. /* All the pipes are now open. */
  277. cp->PipesLeft = KWSYSPE_PIPE_COUNT;
  278. /* The process has now started. */
  279. cp->State = kwsysProcess_State_Executing;
  280. }
  281. /*--------------------------------------------------------------------------*/
  282. int kwsysProcess_WaitForData(kwsysProcess* cp, int pipes, char** data, int* length,
  283. double* userTimeout)
  284. {
  285. int i;
  286. int max = -1;
  287. kwsysProcessTime* timeout = 0;
  288. kwsysProcessTime timeoutLength;
  289. kwsysProcessTime timeoutTime;
  290. kwsysProcessTime userStartTime;
  291. int user = 0;
  292. int expired = 0;
  293. int pipeId = 0;
  294. int numReady = 0;
  295. /* Record the time at which user timeout period starts. */
  296. if(userTimeout)
  297. {
  298. userStartTime = kwsysProcessTimeGetCurrent();
  299. }
  300. /* Calculate the time at which a timeout will expire, and whether it
  301. is the user or process timeout. */
  302. user = kwsysProcessGetTimeoutTime(cp, userTimeout, &timeoutTime);
  303. /* Data can only be available when pipes are open. If the process
  304. is not running, cp->PipesLeft will be 0. */
  305. while(cp->PipesLeft > 0)
  306. {
  307. /* Check for any open pipes with data reported ready by the last
  308. call to select. */
  309. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  310. {
  311. if(cp->PipeReadEnds[i] >= 0 &&
  312. FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  313. {
  314. int n;
  315. /* We are handling this pipe now. Remove it from the set. */
  316. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  317. /* The pipe is ready to read without blocking. Keep trying to
  318. read until the operation is not interrupted. */
  319. while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
  320. KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
  321. if(n > 0)
  322. {
  323. /* We have data on this pipe. */
  324. if(i == KWSYSPE_PIPE_ERROR)
  325. {
  326. /* This is data on the special error reporting pipe. The
  327. child process failed to execute the program. */
  328. cp->ChildError = 1;
  329. if(n > KWSYSPE_PIPE_BUFFER_SIZE - cp->ErrorMessageLength)
  330. {
  331. n = KWSYSPE_PIPE_BUFFER_SIZE - cp->ErrorMessageLength;
  332. }
  333. if(n > 0)
  334. {
  335. memcpy(cp->ErrorMessage+cp->ErrorMessageLength,
  336. cp->PipeBuffer, n);
  337. cp->ErrorMessageLength += n;
  338. cp->ErrorMessage[cp->ErrorMessageLength] = 0;
  339. }
  340. }
  341. else if(pipes & (1 << i))
  342. {
  343. /* Caller wants this data. Report it. */
  344. *data = cp->PipeBuffer;
  345. *length = n;
  346. pipeId = (1 << i);
  347. break;
  348. }
  349. }
  350. else
  351. {
  352. /* We are done reading from this pipe. */
  353. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  354. --cp->PipesLeft;
  355. }
  356. }
  357. }
  358. /* If we have data, break early. */
  359. if(pipeId)
  360. {
  361. break;
  362. }
  363. /* Make sure the set is empty (it should always be empty here
  364. anyway). */
  365. FD_ZERO(&cp->PipeSet);
  366. /* Add the pipe reading ends that are still open. */
  367. max = -1;
  368. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  369. {
  370. if(cp->PipeReadEnds[i] >= 0)
  371. {
  372. FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
  373. if(cp->PipeReadEnds[i] > max)
  374. {
  375. max = cp->PipeReadEnds[i];
  376. }
  377. }
  378. }
  379. /* Make sure we have a non-empty set. */
  380. if(max < 0)
  381. {
  382. /* All pipes have closed. Child has terminated. */
  383. break;
  384. }
  385. /* Setup a timeout if required. */
  386. if(timeoutTime.tv_sec < 0)
  387. {
  388. timeout = 0;
  389. }
  390. else
  391. {
  392. timeout = &timeoutLength;
  393. }
  394. if(kwsysProcessGetTimeoutLeft(&timeoutTime, &timeoutLength))
  395. {
  396. /* Timeout has already expired. */
  397. expired = 1;
  398. break;
  399. }
  400. /* Run select to block until data are available. Repeat call
  401. until it is not interrupted. */
  402. while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
  403. (errno == EINTR));
  404. /* Check result of select. */
  405. if(numReady == 0)
  406. {
  407. /* Select's timeout expired. */
  408. expired = 1;
  409. break;
  410. }
  411. else if(numReady < 0)
  412. {
  413. /* Select returned an error. Leave the error description in the
  414. pipe buffer. */
  415. snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE,
  416. "%s", strerror(errno));
  417. /* Kill the child now. */
  418. kwsysProcess_Kill(cp);
  419. cp->Killed = 0;
  420. cp->ChildError = 1;
  421. cp->PipesLeft = 0;
  422. }
  423. }
  424. /* Update the user timeout. */
  425. if(userTimeout)
  426. {
  427. kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
  428. kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
  429. userStartTime);
  430. double d = kwsysProcessTimeToDouble(difference);
  431. *userTimeout -= d;
  432. if(*userTimeout < 0)
  433. {
  434. *userTimeout = 0;
  435. }
  436. }
  437. /* Check what happened. */
  438. if(pipeId)
  439. {
  440. /* Data are ready on a pipe. */
  441. return pipeId;
  442. }
  443. else if(expired)
  444. {
  445. /* A timeout has expired. */
  446. if(user)
  447. {
  448. /* The user timeout has expired. It has no time left. */
  449. return kwsysProcess_Pipe_Timeout;
  450. }
  451. else
  452. {
  453. /* The process timeout has expired. Kill the child now. */
  454. kwsysProcess_Kill(cp);
  455. cp->Killed = 0;
  456. cp->TimeoutExpired = 1;
  457. cp->PipesLeft = 0;
  458. return 0;
  459. }
  460. }
  461. else
  462. {
  463. /* No pipes are left open. */
  464. return 0;
  465. }
  466. }
  467. /*--------------------------------------------------------------------------*/
  468. int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
  469. {
  470. int result = 0;
  471. int status = 0;
  472. int pipe = 0;
  473. /* Make sure we are executing a process. */
  474. if(cp->State != kwsysProcess_State_Executing)
  475. {
  476. return 1;
  477. }
  478. /* Wait for all the pipes to close. Ignore all data. */
  479. while((pipe = kwsysProcess_WaitForData(cp, 0, 0, 0, userTimeout)) > 0)
  480. {
  481. if(pipe == kwsysProcess_Pipe_Timeout)
  482. {
  483. return 0;
  484. }
  485. }
  486. /* Wait for the child to terminate. The process should have already
  487. exited because KWSYSPE_PIPE_ERROR has been closed by this point.
  488. Repeat the call until it is not interrupted. */
  489. while(((result = waitpid(cp->ForkPID, &status, 0)) < 0) && (errno == EINTR));
  490. if(result <= 0)
  491. {
  492. /* Unexpected error. */
  493. kwsysProcessCleanup(cp, 1);
  494. return 1;
  495. }
  496. /* Check whether the child reported an error invoking the process. */
  497. if(cp->ChildError)
  498. {
  499. /* The error message is already in its buffer. Tell
  500. kwsysProcessCleanup to not create it. */
  501. kwsysProcessCleanup(cp, 0);
  502. cp->State = kwsysProcess_State_Error;
  503. return 1;
  504. }
  505. /* Determine the outcome. */
  506. if(cp->Killed)
  507. {
  508. /* We killed the child. */
  509. cp->State = kwsysProcess_State_Killed;
  510. }
  511. else if(cp->TimeoutExpired)
  512. {
  513. /* The timeout expired. */
  514. cp->State = kwsysProcess_State_Expired;
  515. }
  516. else if(WIFEXITED(status))
  517. {
  518. /* The child exited normally. */
  519. cp->State = kwsysProcess_State_Exited;
  520. cp->ExitException = kwsysProcess_Exception_None;
  521. cp->ExitCode = status;
  522. cp->ExitValue = (int)WEXITSTATUS(status);
  523. }
  524. else if(WIFSIGNALED(status))
  525. {
  526. /* The child received an unhandled signal. */
  527. cp->State = kwsysProcess_State_Exception;
  528. switch ((int)WTERMSIG(status))
  529. {
  530. #ifdef SIGSEGV
  531. case SIGSEGV: cp->ExitException = kwsysProcess_Exception_Fault; break;
  532. #endif
  533. #ifdef SIGFPE
  534. case SIGFPE: cp->ExitException = kwsysProcess_Exception_Numerical; break;
  535. #endif
  536. #ifdef SIGILL
  537. case SIGILL: cp->ExitException = kwsysProcess_Exception_Illegal; break;
  538. #endif
  539. #ifdef SIGINT
  540. case SIGINT: cp->ExitException = kwsysProcess_Exception_Interrupt; break;
  541. #endif
  542. default: cp->ExitException = kwsysProcess_Exception_Other; break;
  543. }
  544. cp->ExitCode = status;
  545. }
  546. else
  547. {
  548. /* Error getting the child return code. */
  549. strcpy(cp->ErrorMessage, "Error getting child return code.");
  550. cp->State = kwsysProcess_State_Error;
  551. }
  552. /* Normal cleanup. */
  553. kwsysProcessCleanup(cp, 0);
  554. return 1;
  555. }
  556. /*--------------------------------------------------------------------------*/
  557. void kwsysProcess_Kill(kwsysProcess* cp)
  558. {
  559. /* Make sure we are executing a process. */
  560. if(cp->State != kwsysProcess_State_Executing)
  561. {
  562. return;
  563. }
  564. /* Kill the child. */
  565. cp->Killed = 1;
  566. kill(cp->ForkPID, SIGKILL);
  567. }
  568. /*--------------------------------------------------------------------------*/
  569. /* Initialize a process control structure for kwsysProcess_Execute. */
  570. static void kwsysProcessInitialize(kwsysProcess* cp)
  571. {
  572. int i;
  573. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  574. {
  575. cp->PipeReadEnds[i] = -1;
  576. cp->PipeWriteEnds[i] = -1;
  577. }
  578. cp->ForkPID = -1;
  579. cp->ChildError = 0;
  580. cp->StartTime.tv_sec = -1;
  581. cp->StartTime.tv_usec = -1;
  582. cp->TimeoutTime.tv_sec = -1;
  583. cp->TimeoutTime.tv_usec = -1;
  584. cp->TimeoutExpired = 0;
  585. cp->PipesLeft = 0;
  586. FD_ZERO(&cp->PipeSet);
  587. cp->State = kwsysProcess_State_Starting;
  588. cp->Killed = 0;
  589. cp->ExitException = kwsysProcess_Exception_None;
  590. cp->ExitCode = 1;
  591. cp->ExitValue = 1;
  592. cp->ErrorMessage[0] = 0;
  593. cp->ErrorMessageLength = 0;
  594. }
  595. /*--------------------------------------------------------------------------*/
  596. /* Free all resources used by the given kwsysProcess instance that were
  597. allocated by kwsysProcess_Execute. */
  598. static void kwsysProcessCleanup(kwsysProcess* cp, int error)
  599. {
  600. int i;
  601. /* If cleaning up due to an error, report the error message. */
  602. if(error)
  603. {
  604. snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE, "%s", strerror(errno));
  605. cp->State = kwsysProcess_State_Error;
  606. }
  607. /* Restore the SIGCHLD handler. */
  608. while((sigaction(SIGCHLD, &cp->OldSigChldAction, 0) < 0) &&
  609. (errno == EINTR));
  610. /* Close pipe handles. */
  611. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  612. {
  613. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  614. kwsysProcessCleanupDescriptor(&cp->PipeWriteEnds[i]);
  615. }
  616. }
  617. /*--------------------------------------------------------------------------*/
  618. /* Close the given file descriptor if it is open. Reset its value to -1. */
  619. static void kwsysProcessCleanupDescriptor(int* pfd)
  620. {
  621. if(pfd && *pfd >= 0)
  622. {
  623. /* Keep trying to close until it is not interrupted by a
  624. * signal. */
  625. while((close(*pfd) < 0) && (errno == EINTR));
  626. *pfd = -1;
  627. }
  628. }
  629. /*--------------------------------------------------------------------------*/
  630. /* Get the time at which either the process or user timeout will
  631. expire. Returns 1 if the user timeout is first, and 0 otherwise. */
  632. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  633. kwsysProcessTime* timeoutTime)
  634. {
  635. /* The first time this is called, we need to calculate the time at
  636. which the child will timeout. */
  637. if(cp->Timeout && cp->TimeoutTime.tv_sec < 0)
  638. {
  639. kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
  640. cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
  641. }
  642. /* Start with process timeout. */
  643. *timeoutTime = cp->TimeoutTime;
  644. /* Check if the user timeout is earlier. */
  645. if(userTimeout)
  646. {
  647. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  648. kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
  649. kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
  650. userTimeoutLength);
  651. if(kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
  652. {
  653. *timeoutTime = userTimeoutTime;
  654. return 1;
  655. }
  656. }
  657. return 0;
  658. }
  659. /*--------------------------------------------------------------------------*/
  660. /* Get the length of time before the given timeout time arrives.
  661. Returns 1 if the time has already arrived, and 0 otherwise. */
  662. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  663. kwsysProcessTime* timeoutLength)
  664. {
  665. if(timeoutTime->tv_sec < 0)
  666. {
  667. /* No timeout time has been requested. */
  668. return 0;
  669. }
  670. else
  671. {
  672. /* Calculate the remaining time. */
  673. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  674. *timeoutLength = kwsysProcessTimeSubtract(*timeoutTime, currentTime);
  675. if(timeoutLength->tv_sec < 0)
  676. {
  677. /* Timeout has already expired. */
  678. return 1;
  679. }
  680. else
  681. {
  682. /* There is some time left. */
  683. return 0;
  684. }
  685. }
  686. }
  687. /*--------------------------------------------------------------------------*/
  688. static kwsysProcessTime kwsysProcessTimeGetCurrent()
  689. {
  690. kwsysProcessTime current;
  691. gettimeofday(&current, 0);
  692. return current;
  693. }
  694. /*--------------------------------------------------------------------------*/
  695. static double kwsysProcessTimeToDouble(kwsysProcessTime t)
  696. {
  697. return (double)t.tv_sec + t.tv_usec*0.000001;
  698. }
  699. /*--------------------------------------------------------------------------*/
  700. static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
  701. {
  702. kwsysProcessTime t;
  703. t.tv_sec = (long)d;
  704. t.tv_usec = (long)((d-t.tv_sec)*1000000);
  705. return t;
  706. }
  707. /*--------------------------------------------------------------------------*/
  708. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
  709. {
  710. return ((in1.tv_sec < in2.tv_sec) ||
  711. ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
  712. }
  713. /*--------------------------------------------------------------------------*/
  714. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
  715. {
  716. kwsysProcessTime out;
  717. out.tv_sec = in1.tv_sec + in2.tv_sec;
  718. out.tv_usec = in1.tv_usec + in2.tv_usec;
  719. if(out.tv_usec > 1000000)
  720. {
  721. out.tv_usec -= 1000000;
  722. out.tv_sec += 1;
  723. }
  724. return out;
  725. }
  726. /*--------------------------------------------------------------------------*/
  727. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
  728. {
  729. kwsysProcessTime out;
  730. out.tv_sec = in1.tv_sec - in2.tv_sec;
  731. out.tv_usec = in1.tv_usec - in2.tv_usec;
  732. if(out.tv_usec < 0)
  733. {
  734. out.tv_usec += 1000000;
  735. out.tv_sec -= 1;
  736. }
  737. return out;
  738. }
  739. /*--------------------------------------------------------------------------*/
  740. /* When the child process encounters an error before its program is
  741. invoked, this is called to report the error to the parent and
  742. exit. */
  743. static void kwsysProcessChildErrorExit(kwsysProcess* cp)
  744. {
  745. /* Construct the error message. */
  746. char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
  747. snprintf(buffer, KWSYSPE_PIPE_BUFFER_SIZE, "%s", strerror(errno));
  748. /* Report the error to the parent through the special pipe. */
  749. write(cp->PipeWriteEnds[KWSYSPE_PIPE_ERROR], buffer, strlen(buffer));
  750. /* Terminate without cleanup. */
  751. _exit(1);
  752. }
  753. /*--------------------------------------------------------------------------*/
  754. /* Restores all signal handlers to their default values. */
  755. static void kwsysProcessRestoreDefaultSignalHandlers()
  756. {
  757. struct sigaction act;
  758. act.sa_handler = SIG_DFL;
  759. #ifdef SIGHUP
  760. sigaction(SIGHUP, &act, 0);
  761. #endif
  762. #ifdef SIGINT
  763. sigaction(SIGINT, &act, 0);
  764. #endif
  765. #ifdef SIGQUIT
  766. sigaction(SIGQUIT, &act, 0);
  767. #endif
  768. #ifdef SIGILL
  769. sigaction(SIGILL, &act, 0);
  770. #endif
  771. #ifdef SIGTRAP
  772. sigaction(SIGTRAP, &act, 0);
  773. #endif
  774. #ifdef SIGABRT
  775. sigaction(SIGABRT, &act, 0);
  776. #endif
  777. #ifdef SIGIOT
  778. sigaction(SIGIOT, &act, 0);
  779. #endif
  780. #ifdef SIGBUS
  781. sigaction(SIGBUS, &act, 0);
  782. #endif
  783. #ifdef SIGFPE
  784. sigaction(SIGFPE, &act, 0);
  785. #endif
  786. #ifdef SIGUSR1
  787. sigaction(SIGUSR1, &act, 0);
  788. #endif
  789. #ifdef SIGSEGV
  790. sigaction(SIGSEGV, &act, 0);
  791. #endif
  792. #ifdef SIGUSR2
  793. sigaction(SIGUSR2, &act, 0);
  794. #endif
  795. #ifdef SIGPIPE
  796. sigaction(SIGPIPE, &act, 0);
  797. #endif
  798. #ifdef SIGALRM
  799. sigaction(SIGALRM, &act, 0);
  800. #endif
  801. #ifdef SIGTERM
  802. sigaction(SIGTERM, &act, 0);
  803. #endif
  804. #ifdef SIGSTKFLT
  805. sigaction(SIGSTKFLT, &act, 0);
  806. #endif
  807. #ifdef SIGCLD
  808. sigaction(SIGCLD, &act, 0);
  809. #endif
  810. #ifdef SIGCHLD
  811. sigaction(SIGCHLD, &act, 0);
  812. #endif
  813. #ifdef SIGCONT
  814. sigaction(SIGCONT, &act, 0);
  815. #endif
  816. #ifdef SIGTSTP
  817. sigaction(SIGTSTP, &act, 0);
  818. #endif
  819. #ifdef SIGTTIN
  820. sigaction(SIGTTIN, &act, 0);
  821. #endif
  822. #ifdef SIGTTOU
  823. sigaction(SIGTTOU, &act, 0);
  824. #endif
  825. #ifdef SIGURG
  826. sigaction(SIGURG, &act, 0);
  827. #endif
  828. #ifdef SIGXCPU
  829. sigaction(SIGXCPU, &act, 0);
  830. #endif
  831. #ifdef SIGXFSZ
  832. sigaction(SIGXFSZ, &act, 0);
  833. #endif
  834. #ifdef SIGVTALRM
  835. sigaction(SIGVTALRM, &act, 0);
  836. #endif
  837. #ifdef SIGPROF
  838. sigaction(SIGPROF, &act, 0);
  839. #endif
  840. #ifdef SIGWINCH
  841. sigaction(SIGWINCH, &act, 0);
  842. #endif
  843. #ifdef SIGPOLL
  844. sigaction(SIGPOLL, &act, 0);
  845. #endif
  846. #ifdef SIGIO
  847. sigaction(SIGIO, &act, 0);
  848. #endif
  849. #ifdef SIGPWR
  850. sigaction(SIGPWR, &act, 0);
  851. #endif
  852. #ifdef SIGSYS
  853. sigaction(SIGSYS, &act, 0);
  854. #endif
  855. #ifdef SIGUNUSED
  856. sigaction(SIGUNUSED, &act, 0);
  857. #endif
  858. }