ProcessUNIX.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. /*=========================================================================
  2. Program: KWSys - Kitware System Library
  3. Module: $RCSfile$
  4. Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
  5. See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even
  7. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  8. PURPOSE. See the above copyright notices for more information.
  9. =========================================================================*/
  10. #define KWSYS_IN_PROCESS_C
  11. #include "kwsysPrivate.h"
  12. #include KWSYS_HEADER(Process.h)
  13. /*
  14. Implementation for UNIX
  15. On UNIX, a child process is forked to exec the program. Three
  16. output pipes from the child are read by the parent process using a
  17. select call to block until data are ready. Two of the pipes are
  18. stdout and stderr for the child. The third is a special error pipe
  19. that has two purposes. First, if the child cannot exec the program,
  20. the error is reported through the error pipe. Second, the error
  21. pipe is left open until the child exits. This is used in
  22. conjunction with the timeout on the select call to implement a
  23. timeout for program even when it closes stdout and stderr.
  24. */
  25. /*
  26. TODO:
  27. We cannot create the pipeline of processes in suspended states. How
  28. do we cleanup processes already started when one fails to load? Right
  29. now we are just killing them, which is probably not the right thing to
  30. do.
  31. */
  32. #include <stdio.h> /* snprintf */
  33. #include <stdlib.h> /* malloc, free */
  34. #include <string.h> /* strdup, strerror, memset */
  35. #include <sys/time.h> /* struct timeval */
  36. #include <sys/types.h> /* pid_t, fd_set */
  37. #include <sys/wait.h> /* waitpid */
  38. #include <sys/stat.h> /* open mode */
  39. #include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
  40. #include <fcntl.h> /* fcntl */
  41. #include <errno.h> /* errno */
  42. #include <time.h> /* gettimeofday */
  43. #include <signal.h> /* sigaction */
  44. /* The number of pipes for the child's output. The standard stdout
  45. and stderr pipes are the first two. One more pipe is used to
  46. detect when the child process has terminated. The third pipe is
  47. not given to the child process, so it cannot close it until it
  48. terminates. */
  49. #define KWSYSPE_PIPE_COUNT 3
  50. #define KWSYSPE_PIPE_STDOUT 0
  51. #define KWSYSPE_PIPE_STDERR 1
  52. #define KWSYSPE_PIPE_TERM 2
  53. /* The maximum amount to read from a pipe at a time. */
  54. #define KWSYSPE_PIPE_BUFFER_SIZE 1024
  55. typedef struct timeval kwsysProcessTime;
  56. typedef struct kwsysProcessCreateInformation_s
  57. {
  58. int StdIn;
  59. int StdOut;
  60. int StdErr;
  61. int TermPipe;
  62. int ErrorPipe[2];
  63. } kwsysProcessCreateInformation;
  64. /*--------------------------------------------------------------------------*/
  65. static int kwsysProcessInitialize(kwsysProcess* cp);
  66. static void kwsysProcessCleanup(kwsysProcess* cp, int error);
  67. static void kwsysProcessCleanupDescriptor(int* pfd);
  68. static int kwsysProcessCreate(kwsysProcess* cp, int index,
  69. kwsysProcessCreateInformation* si, int* readEnd);
  70. static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
  71. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  72. kwsysProcessTime* timeoutTime);
  73. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  74. kwsysProcessTime* timeoutLength);
  75. static kwsysProcessTime kwsysProcessTimeGetCurrent();
  76. static double kwsysProcessTimeToDouble(kwsysProcessTime t);
  77. static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
  78. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
  79. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
  80. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
  81. static void kwsysProcessChildErrorExit(int errorPipe);
  82. static void kwsysProcessRestoreDefaultSignalHandlers();
  83. /*--------------------------------------------------------------------------*/
  84. /* Structure containing data used to implement the child's execution. */
  85. struct kwsysProcess_s
  86. {
  87. /* The command lines to execute. */
  88. char*** Commands;
  89. int NumberOfCommands;
  90. /* Descriptors for the read ends of the child's output pipes. */
  91. int PipeReadEnds[KWSYSPE_PIPE_COUNT];
  92. /* Buffer for pipe data. */
  93. char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
  94. /* Process IDs returned by the calls to fork. */
  95. pid_t* ForkPIDs;
  96. /* Flag for whether the children were terminated by a faild select. */
  97. int SelectError;
  98. /* The timeout length. */
  99. double Timeout;
  100. /* The working directory for the process. */
  101. char* WorkingDirectory;
  102. /* Time at which the child started. Negative for no timeout. */
  103. kwsysProcessTime StartTime;
  104. /* Time at which the child will timeout. Negative for no timeout. */
  105. kwsysProcessTime TimeoutTime;
  106. /* Flag for whether the timeout expired. */
  107. int TimeoutExpired;
  108. /* The old SIGCHLD handler. */
  109. struct sigaction OldSigChldAction;
  110. /* The number of pipes left open during execution. */
  111. int PipesLeft;
  112. /* File descriptor set for call to select. */
  113. fd_set PipeSet;
  114. /* The current status of the child process. */
  115. int State;
  116. /* The exceptional behavior that terminated the child process, if
  117. * any. */
  118. int ExitException;
  119. /* The exit code of the child process. */
  120. int ExitCode;
  121. /* The exit value of the child process, if any. */
  122. int ExitValue;
  123. /* Whether the process was killed. */
  124. int Killed;
  125. /* Buffer for error message in case of failure. */
  126. char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
  127. /* The exit codes of each child process in the pipeline. */
  128. int* CommandExitCodes;
  129. /* Name of files to which stdin and stdout pipes are attached. */
  130. char* PipeFileSTDIN;
  131. char* PipeFileSTDOUT;
  132. char* PipeFileSTDERR;
  133. /* Whether each pipe is shared with the parent process. */
  134. int PipeSharedSTDIN;
  135. int PipeSharedSTDOUT;
  136. int PipeSharedSTDERR;
  137. /* The real working directory of this process. */
  138. int RealWorkingDirectoryLength;
  139. char* RealWorkingDirectory;
  140. };
  141. /*--------------------------------------------------------------------------*/
  142. kwsysProcess* kwsysProcess_New()
  143. {
  144. /* Allocate a process control structure. */
  145. kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
  146. if(!cp)
  147. {
  148. return 0;
  149. }
  150. memset(cp, 0, sizeof(kwsysProcess));
  151. /* Share stdin with the parent process by default. */
  152. cp->PipeSharedSTDIN = 1;
  153. /* Set initial status. */
  154. cp->State = kwsysProcess_State_Starting;
  155. return cp;
  156. }
  157. /*--------------------------------------------------------------------------*/
  158. void kwsysProcess_Delete(kwsysProcess* cp)
  159. {
  160. /* Make sure we have an instance. */
  161. if(!cp)
  162. {
  163. return;
  164. }
  165. /* If the process is executing, wait for it to finish. */
  166. if(cp->State == kwsysProcess_State_Executing)
  167. {
  168. kwsysProcess_WaitForExit(cp, 0);
  169. }
  170. /* Free memory. */
  171. kwsysProcess_SetCommand(cp, 0);
  172. kwsysProcess_SetWorkingDirectory(cp, 0);
  173. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
  174. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
  175. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
  176. if(cp->CommandExitCodes)
  177. {
  178. free(cp->CommandExitCodes);
  179. }
  180. free(cp);
  181. }
  182. /*--------------------------------------------------------------------------*/
  183. int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
  184. {
  185. int i;
  186. if(!cp)
  187. {
  188. return 0;
  189. }
  190. for(i=0; i < cp->NumberOfCommands; ++i)
  191. {
  192. char** c = cp->Commands[i];
  193. while(*c)
  194. {
  195. free(*c++);
  196. }
  197. free(cp->Commands[i]);
  198. }
  199. cp->NumberOfCommands = 0;
  200. if(cp->Commands)
  201. {
  202. free(cp->Commands);
  203. cp->Commands = 0;
  204. }
  205. if(command)
  206. {
  207. return kwsysProcess_AddCommand(cp, command);
  208. }
  209. return 1;
  210. }
  211. /*--------------------------------------------------------------------------*/
  212. int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
  213. {
  214. int newNumberOfCommands;
  215. char*** newCommands;
  216. /* Make sure we have a command to add. */
  217. if(!cp || !command)
  218. {
  219. return 0;
  220. }
  221. /* Allocate a new array for command pointers. */
  222. newNumberOfCommands = cp->NumberOfCommands + 1;
  223. if(!(newCommands = (char***)malloc(sizeof(char**) * newNumberOfCommands)))
  224. {
  225. /* Out of memory. */
  226. return 0;
  227. }
  228. /* Copy any existing commands into the new array. */
  229. {
  230. int i;
  231. for(i=0; i < cp->NumberOfCommands; ++i)
  232. {
  233. newCommands[i] = cp->Commands[i];
  234. }
  235. }
  236. /* Add the new command. */
  237. {
  238. char const* const* c = command;
  239. int n = 0;
  240. int i = 0;
  241. while(*c++);
  242. n = c - command - 1;
  243. newCommands[cp->NumberOfCommands] = (char**)malloc((n+1)*sizeof(char*));
  244. if(!newCommands[cp->NumberOfCommands])
  245. {
  246. /* Out of memory. */
  247. free(newCommands);
  248. return 0;
  249. }
  250. for(i=0; i < n; ++i)
  251. {
  252. newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
  253. if(!newCommands[cp->NumberOfCommands][i])
  254. {
  255. break;
  256. }
  257. }
  258. if(i < n)
  259. {
  260. /* Out of memory. */
  261. for(;i > 0; --i)
  262. {
  263. free(newCommands[cp->NumberOfCommands][i-1]);
  264. }
  265. free(newCommands);
  266. return 0;
  267. }
  268. newCommands[cp->NumberOfCommands][n] = 0;
  269. }
  270. /* Successfully allocated new command array. Free the old array. */
  271. free(cp->Commands);
  272. cp->Commands = newCommands;
  273. cp->NumberOfCommands = newNumberOfCommands;
  274. return 1;
  275. }
  276. /*--------------------------------------------------------------------------*/
  277. void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
  278. {
  279. if(!cp)
  280. {
  281. return;
  282. }
  283. cp->Timeout = timeout;
  284. if(cp->Timeout < 0)
  285. {
  286. cp->Timeout = 0;
  287. }
  288. }
  289. /*--------------------------------------------------------------------------*/
  290. int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
  291. {
  292. if(!cp)
  293. {
  294. return 0;
  295. }
  296. if(cp->WorkingDirectory == dir)
  297. {
  298. return 1;
  299. }
  300. if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
  301. {
  302. return 1;
  303. }
  304. if(cp->WorkingDirectory)
  305. {
  306. free(cp->WorkingDirectory);
  307. cp->WorkingDirectory = 0;
  308. }
  309. if(dir)
  310. {
  311. cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
  312. if(!cp->WorkingDirectory)
  313. {
  314. return 0;
  315. }
  316. strcpy(cp->WorkingDirectory, dir);
  317. }
  318. return 1;
  319. }
  320. /*--------------------------------------------------------------------------*/
  321. int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file)
  322. {
  323. char** pfile;
  324. if(!cp)
  325. {
  326. return 0;
  327. }
  328. switch(pipe)
  329. {
  330. case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
  331. case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
  332. case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
  333. default: return 0;
  334. }
  335. if(*pfile)
  336. {
  337. free(*pfile);
  338. *pfile = 0;
  339. }
  340. if(file)
  341. {
  342. *pfile = malloc(strlen(file)+1);
  343. if(!*pfile)
  344. {
  345. return 0;
  346. }
  347. strcpy(*pfile, file);
  348. }
  349. /* If we are redirecting the pipe, do not share it. */
  350. if(*pfile)
  351. {
  352. kwsysProcess_SetPipeShared(cp, pipe, 0);
  353. }
  354. return 1;
  355. }
  356. /*--------------------------------------------------------------------------*/
  357. void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe, int shared)
  358. {
  359. if(!cp)
  360. {
  361. return;
  362. }
  363. switch(pipe)
  364. {
  365. case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
  366. case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
  367. case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
  368. default: return;
  369. }
  370. /* If we are sharing the pipe, do not redirect it to a file. */
  371. if(shared)
  372. {
  373. kwsysProcess_SetPipeFile(cp, pipe, 0);
  374. }
  375. }
  376. /*--------------------------------------------------------------------------*/
  377. int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
  378. {
  379. (void)cp;
  380. (void)optionId;
  381. return 0;
  382. }
  383. /*--------------------------------------------------------------------------*/
  384. void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
  385. {
  386. (void)cp;
  387. (void)optionId;
  388. (void)value;
  389. }
  390. /*--------------------------------------------------------------------------*/
  391. int kwsysProcess_GetState(kwsysProcess* cp)
  392. {
  393. return cp? cp->State : kwsysProcess_State_Error;
  394. }
  395. /*--------------------------------------------------------------------------*/
  396. int kwsysProcess_GetExitException(kwsysProcess* cp)
  397. {
  398. return cp? cp->ExitException : kwsysProcess_Exception_Other;
  399. }
  400. /*--------------------------------------------------------------------------*/
  401. int kwsysProcess_GetExitCode(kwsysProcess* cp)
  402. {
  403. return cp? cp->ExitCode : 0;
  404. }
  405. /*--------------------------------------------------------------------------*/
  406. int kwsysProcess_GetExitValue(kwsysProcess* cp)
  407. {
  408. return cp? cp->ExitValue : -1;
  409. }
  410. /*--------------------------------------------------------------------------*/
  411. const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
  412. {
  413. if(!cp)
  414. {
  415. return "Process management structure could not be allocated.";
  416. }
  417. else if(cp->State == kwsysProcess_State_Error)
  418. {
  419. return cp->ErrorMessage;
  420. }
  421. return 0;
  422. }
  423. /*--------------------------------------------------------------------------*/
  424. void kwsysProcess_Execute(kwsysProcess* cp)
  425. {
  426. int i;
  427. struct sigaction newSigChldAction;
  428. kwsysProcessCreateInformation si = {-1, -1, -1, -1, {-1, -1}};
  429. /* Do not execute a second copy simultaneously. */
  430. if(!cp || cp->State == kwsysProcess_State_Executing)
  431. {
  432. return;
  433. }
  434. /* Initialize the control structure for a new process. */
  435. if(!kwsysProcessInitialize(cp))
  436. {
  437. strcpy(cp->ErrorMessage, "Out of memory");
  438. cp->State = kwsysProcess_State_Error;
  439. return;
  440. }
  441. /* Save the real working directory of this process and change to
  442. the working directory for the child processes. This is needed
  443. to make pipe file paths evaluate correctly. */
  444. if(cp->WorkingDirectory)
  445. {
  446. int r;
  447. if(!getcwd(cp->RealWorkingDirectory, cp->RealWorkingDirectoryLength))
  448. {
  449. kwsysProcessCleanup(cp, 1);
  450. return;
  451. }
  452. /* Some platforms specify that the chdir call may be
  453. interrupted. Repeat the call until it finishes. */
  454. while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
  455. if(r < 0)
  456. {
  457. kwsysProcessCleanup(cp, 1);
  458. }
  459. }
  460. /* We want no special handling of SIGCHLD. Repeat call until it is
  461. not interrupted. */
  462. memset(&newSigChldAction, 0, sizeof(struct sigaction));
  463. newSigChldAction.sa_handler = SIG_DFL;
  464. while((sigaction(SIGCHLD, &newSigChldAction, &cp->OldSigChldAction) < 0) &&
  465. (errno == EINTR));
  466. /* Setup the stderr and termination pipes to be shared by all processes. */
  467. for(i=KWSYSPE_PIPE_STDERR; i < KWSYSPE_PIPE_COUNT; ++i)
  468. {
  469. /* Create the pipe. */
  470. int p[2];
  471. if(pipe(p) < 0)
  472. {
  473. kwsysProcessCleanup(cp, 1);
  474. return;
  475. }
  476. /* Store the pipe. */
  477. cp->PipeReadEnds[i] = p[0];
  478. if(i == KWSYSPE_PIPE_STDERR)
  479. {
  480. si.StdErr = p[1];
  481. }
  482. else
  483. {
  484. si.TermPipe = p[1];
  485. }
  486. /* Set close-on-exec flag on the pipe's ends. */
  487. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  488. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  489. {
  490. kwsysProcessCleanup(cp, 1);
  491. kwsysProcessCleanupDescriptor(&si.StdErr);
  492. kwsysProcessCleanupDescriptor(&si.TermPipe);
  493. return;
  494. }
  495. }
  496. /* Replace the stderr pipe with a file if requested. In this case
  497. the select call will report that stderr is closed immediately. */
  498. if(cp->PipeFileSTDERR)
  499. {
  500. if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
  501. {
  502. kwsysProcessCleanup(cp, 1);
  503. kwsysProcessCleanupDescriptor(&si.StdErr);
  504. kwsysProcessCleanupDescriptor(&si.TermPipe);
  505. return;
  506. }
  507. }
  508. /* Replace the stderr pipe with the parent's if requested. In this
  509. case the select call will report that stderr is closed
  510. immediately. */
  511. if(cp->PipeSharedSTDERR)
  512. {
  513. kwsysProcessCleanupDescriptor(&si.StdErr);
  514. si.StdErr = 2;
  515. }
  516. /* The timeout period starts now. */
  517. cp->StartTime = kwsysProcessTimeGetCurrent();
  518. cp->TimeoutTime.tv_sec = -1;
  519. cp->TimeoutTime.tv_usec = -1;
  520. /* Create the pipeline of processes. */
  521. {
  522. int readEnd = -1;
  523. for(i=0; i < cp->NumberOfCommands; ++i)
  524. {
  525. if(!kwsysProcessCreate(cp, i, &si, &readEnd))
  526. {
  527. kwsysProcessCleanup(cp, 1);
  528. /* Release resources that may have been allocated for this
  529. process before an error occurred. */
  530. kwsysProcessCleanupDescriptor(&readEnd);
  531. if(si.StdIn != 0)
  532. {
  533. kwsysProcessCleanupDescriptor(&si.StdIn);
  534. }
  535. if(si.StdOut != 1)
  536. {
  537. kwsysProcessCleanupDescriptor(&si.StdOut);
  538. }
  539. if(si.StdErr != 2)
  540. {
  541. kwsysProcessCleanupDescriptor(&si.StdErr);
  542. }
  543. kwsysProcessCleanupDescriptor(&si.TermPipe);
  544. kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
  545. kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
  546. return;
  547. }
  548. }
  549. /* Save a handle to the output pipe for the last process. */
  550. cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
  551. }
  552. /* The parent process does not need the output pipe write ends. */
  553. kwsysProcessCleanupDescriptor(&si.StdErr);
  554. kwsysProcessCleanupDescriptor(&si.TermPipe);
  555. /* Restore the working directory. */
  556. if(cp->RealWorkingDirectory)
  557. {
  558. /* Some platforms specify that the chdir call may be
  559. interrupted. Repeat the call until it finishes. */
  560. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  561. free(cp->RealWorkingDirectory);
  562. cp->RealWorkingDirectory = 0;
  563. }
  564. /* All the pipes are now open. */
  565. cp->PipesLeft = KWSYSPE_PIPE_COUNT;
  566. /* The process has now started. */
  567. cp->State = kwsysProcess_State_Executing;
  568. }
  569. /*--------------------------------------------------------------------------*/
  570. int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
  571. double* userTimeout)
  572. {
  573. int i;
  574. int max = -1;
  575. kwsysProcessTime* timeout = 0;
  576. kwsysProcessTime timeoutLength;
  577. kwsysProcessTime timeoutTime;
  578. kwsysProcessTime userStartTime;
  579. int user = 0;
  580. int expired = 0;
  581. int pipeId = kwsysProcess_Pipe_None;
  582. int numReady = 0;
  583. /* Make sure we are executing a process. */
  584. if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
  585. cp->TimeoutExpired)
  586. {
  587. return kwsysProcess_Pipe_None;
  588. }
  589. /* Record the time at which user timeout period starts. */
  590. if(userTimeout)
  591. {
  592. userStartTime = kwsysProcessTimeGetCurrent();
  593. }
  594. /* Calculate the time at which a timeout will expire, and whether it
  595. is the user or process timeout. */
  596. user = kwsysProcessGetTimeoutTime(cp, userTimeout, &timeoutTime);
  597. /* Data can only be available when pipes are open. If the process
  598. is not running, cp->PipesLeft will be 0. */
  599. while(cp->PipesLeft > 0)
  600. {
  601. /* Check for any open pipes with data reported ready by the last
  602. call to select. */
  603. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  604. {
  605. if(cp->PipeReadEnds[i] >= 0 &&
  606. FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  607. {
  608. int n;
  609. /* We are handling this pipe now. Remove it from the set. */
  610. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  611. /* The pipe is ready to read without blocking. Keep trying to
  612. read until the operation is not interrupted. */
  613. while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
  614. KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
  615. if(n > 0)
  616. {
  617. /* We have data on this pipe. */
  618. if(i == KWSYSPE_PIPE_TERM)
  619. {
  620. /* This is data on the special termination pipe. Ignore it. */
  621. }
  622. else if(data && length)
  623. {
  624. /* Report this data. */
  625. *data = cp->PipeBuffer;
  626. *length = n;
  627. switch(i)
  628. {
  629. case KWSYSPE_PIPE_STDOUT:
  630. pipeId = kwsysProcess_Pipe_STDOUT; break;
  631. case KWSYSPE_PIPE_STDERR:
  632. pipeId = kwsysProcess_Pipe_STDERR; break;
  633. };
  634. break;
  635. }
  636. }
  637. else
  638. {
  639. /* We are done reading from this pipe. */
  640. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  641. --cp->PipesLeft;
  642. }
  643. }
  644. }
  645. /* If we have data, break early. */
  646. if(pipeId)
  647. {
  648. break;
  649. }
  650. /* Make sure the set is empty (it should always be empty here
  651. anyway). */
  652. FD_ZERO(&cp->PipeSet);
  653. /* Add the pipe reading ends that are still open. */
  654. max = -1;
  655. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  656. {
  657. if(cp->PipeReadEnds[i] >= 0)
  658. {
  659. FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
  660. if(cp->PipeReadEnds[i] > max)
  661. {
  662. max = cp->PipeReadEnds[i];
  663. }
  664. }
  665. }
  666. /* Make sure we have a non-empty set. */
  667. if(max < 0)
  668. {
  669. /* All pipes have closed. Child has terminated. */
  670. break;
  671. }
  672. /* Setup a timeout if required. */
  673. if(timeoutTime.tv_sec < 0)
  674. {
  675. timeout = 0;
  676. }
  677. else
  678. {
  679. timeout = &timeoutLength;
  680. }
  681. if(kwsysProcessGetTimeoutLeft(&timeoutTime, &timeoutLength))
  682. {
  683. /* Timeout has already expired. */
  684. expired = 1;
  685. break;
  686. }
  687. /* Run select to block until data are available. Repeat call
  688. until it is not interrupted. */
  689. while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
  690. (errno == EINTR));
  691. /* Check result of select. */
  692. if(numReady == 0)
  693. {
  694. /* Select's timeout expired. */
  695. expired = 1;
  696. break;
  697. }
  698. else if(numReady < 0)
  699. {
  700. /* Select returned an error. Leave the error description in the
  701. pipe buffer. */
  702. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  703. /* Kill the children now. */
  704. kwsysProcess_Kill(cp);
  705. cp->Killed = 0;
  706. cp->SelectError = 1;
  707. cp->PipesLeft = 0;
  708. }
  709. }
  710. /* Update the user timeout. */
  711. if(userTimeout)
  712. {
  713. kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
  714. kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
  715. userStartTime);
  716. double d = kwsysProcessTimeToDouble(difference);
  717. *userTimeout -= d;
  718. if(*userTimeout < 0)
  719. {
  720. *userTimeout = 0;
  721. }
  722. }
  723. /* Check what happened. */
  724. if(pipeId)
  725. {
  726. /* Data are ready on a pipe. */
  727. return pipeId;
  728. }
  729. else if(expired)
  730. {
  731. /* A timeout has expired. */
  732. if(user)
  733. {
  734. /* The user timeout has expired. It has no time left. */
  735. return kwsysProcess_Pipe_Timeout;
  736. }
  737. else
  738. {
  739. /* The process timeout has expired. Kill the children now. */
  740. kwsysProcess_Kill(cp);
  741. cp->Killed = 0;
  742. cp->TimeoutExpired = 1;
  743. cp->PipesLeft = 0;
  744. return kwsysProcess_Pipe_None;
  745. }
  746. }
  747. else
  748. {
  749. /* No pipes are left open. */
  750. return kwsysProcess_Pipe_None;
  751. }
  752. }
  753. /*--------------------------------------------------------------------------*/
  754. int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
  755. {
  756. int result = 0;
  757. int status = 0;
  758. int pipe = 0;
  759. /* Make sure we are executing a process. */
  760. if(!cp || cp->State != kwsysProcess_State_Executing)
  761. {
  762. return 1;
  763. }
  764. /* Wait for all the pipes to close. Ignore all data. */
  765. while((pipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
  766. {
  767. if(pipe == kwsysProcess_Pipe_Timeout)
  768. {
  769. return 0;
  770. }
  771. }
  772. /* Wait for each child to terminate. The process should have
  773. already exited because KWSYSPE_PIPE_TERM has been closed by this
  774. point. Repeat the call until it is not interrupted. */
  775. {
  776. int i;
  777. for(i=0; i < cp->NumberOfCommands; ++i)
  778. {
  779. while(((result = waitpid(cp->ForkPIDs[i],
  780. &cp->CommandExitCodes[i], 0)) < 0) &&
  781. (errno == EINTR));
  782. if(result <= 0 && cp->State != kwsysProcess_State_Error)
  783. {
  784. /* Unexpected error. Report the first time this happens. */
  785. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  786. cp->State = kwsysProcess_State_Error;
  787. }
  788. }
  789. }
  790. /* Check if there was an error in one of the waitpid calls. */
  791. if(cp->State == kwsysProcess_State_Error)
  792. {
  793. /* The error message is already in its buffer. Tell
  794. kwsysProcessCleanup to not create it. */
  795. kwsysProcessCleanup(cp, 0);
  796. return 1;
  797. }
  798. /* Check whether the child reported an error invoking the process. */
  799. if(cp->SelectError)
  800. {
  801. /* The error message is already in its buffer. Tell
  802. kwsysProcessCleanup to not create it. */
  803. kwsysProcessCleanup(cp, 0);
  804. cp->State = kwsysProcess_State_Error;
  805. return 1;
  806. }
  807. /* Use the status of the last process in the pipeline. */
  808. status = cp->CommandExitCodes[cp->NumberOfCommands-1];
  809. /* Determine the outcome. */
  810. if(cp->Killed)
  811. {
  812. /* We killed the child. */
  813. cp->State = kwsysProcess_State_Killed;
  814. }
  815. else if(cp->TimeoutExpired)
  816. {
  817. /* The timeout expired. */
  818. cp->State = kwsysProcess_State_Expired;
  819. }
  820. else if(WIFEXITED(status))
  821. {
  822. /* The child exited normally. */
  823. cp->State = kwsysProcess_State_Exited;
  824. cp->ExitException = kwsysProcess_Exception_None;
  825. cp->ExitCode = status;
  826. cp->ExitValue = (int)WEXITSTATUS(status);
  827. }
  828. else if(WIFSIGNALED(status))
  829. {
  830. /* The child received an unhandled signal. */
  831. cp->State = kwsysProcess_State_Exception;
  832. switch ((int)WTERMSIG(status))
  833. {
  834. #ifdef SIGSEGV
  835. case SIGSEGV: cp->ExitException = kwsysProcess_Exception_Fault; break;
  836. #endif
  837. #ifdef SIGBUS
  838. case SIGBUS: cp->ExitException = kwsysProcess_Exception_Fault; break;
  839. #endif
  840. #ifdef SIGFPE
  841. case SIGFPE: cp->ExitException = kwsysProcess_Exception_Numerical; break;
  842. #endif
  843. #ifdef SIGILL
  844. case SIGILL: cp->ExitException = kwsysProcess_Exception_Illegal; break;
  845. #endif
  846. #ifdef SIGINT
  847. case SIGINT: cp->ExitException = kwsysProcess_Exception_Interrupt; break;
  848. #endif
  849. default: cp->ExitException = kwsysProcess_Exception_Other; break;
  850. }
  851. cp->ExitCode = status;
  852. }
  853. else
  854. {
  855. /* Error getting the child return code. */
  856. strcpy(cp->ErrorMessage, "Error getting child return code.");
  857. cp->State = kwsysProcess_State_Error;
  858. }
  859. /* Normal cleanup. */
  860. kwsysProcessCleanup(cp, 0);
  861. return 1;
  862. }
  863. /*--------------------------------------------------------------------------*/
  864. void kwsysProcess_Kill(kwsysProcess* cp)
  865. {
  866. int i;
  867. /* Make sure we are executing a process. */
  868. if(!cp || cp->State != kwsysProcess_State_Executing)
  869. {
  870. return;
  871. }
  872. /* Kill the children. */
  873. cp->Killed = 1;
  874. for(i=0; i < cp->NumberOfCommands; ++i)
  875. {
  876. if(cp->ForkPIDs[i])
  877. {
  878. kill(cp->ForkPIDs[i], SIGKILL);
  879. }
  880. }
  881. }
  882. /*--------------------------------------------------------------------------*/
  883. /* Initialize a process control structure for kwsysProcess_Execute. */
  884. static int kwsysProcessInitialize(kwsysProcess* cp)
  885. {
  886. int i;
  887. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  888. {
  889. cp->PipeReadEnds[i] = -1;
  890. }
  891. cp->SelectError = 0;
  892. cp->StartTime.tv_sec = -1;
  893. cp->StartTime.tv_usec = -1;
  894. cp->TimeoutTime.tv_sec = -1;
  895. cp->TimeoutTime.tv_usec = -1;
  896. cp->TimeoutExpired = 0;
  897. cp->PipesLeft = 0;
  898. FD_ZERO(&cp->PipeSet);
  899. cp->State = kwsysProcess_State_Starting;
  900. cp->Killed = 0;
  901. cp->ExitException = kwsysProcess_Exception_None;
  902. cp->ExitCode = 1;
  903. cp->ExitValue = 1;
  904. cp->ErrorMessage[0] = 0;
  905. if(cp->ForkPIDs)
  906. {
  907. free(cp->ForkPIDs);
  908. }
  909. cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*cp->NumberOfCommands);
  910. if(!cp->ForkPIDs)
  911. {
  912. return 0;
  913. }
  914. memset(cp->ForkPIDs, 0, sizeof(pid_t)*cp->NumberOfCommands);
  915. if(cp->CommandExitCodes)
  916. {
  917. free(cp->CommandExitCodes);
  918. }
  919. cp->CommandExitCodes = (int*)malloc(sizeof(int)*cp->NumberOfCommands);
  920. if(!cp->CommandExitCodes)
  921. {
  922. return 0;
  923. }
  924. memset(cp->CommandExitCodes, 0, sizeof(int)*cp->NumberOfCommands);
  925. /* Allocate memory to save the real working directory. */
  926. {
  927. #if defined(MAXPATHLEN)
  928. cp->RealWorkingDirectoryLength = MAXPATHLEN;
  929. #elif defined(PATH_MAX)
  930. cp->RealWorkingDirectoryLength = PATH_MAX;
  931. #else
  932. cp->RealWorkingDirectoryLength = 4096;
  933. #endif
  934. cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength);
  935. if(!cp->RealWorkingDirectory)
  936. {
  937. return 0;
  938. }
  939. }
  940. return 1;
  941. }
  942. /*--------------------------------------------------------------------------*/
  943. /* Free all resources used by the given kwsysProcess instance that were
  944. allocated by kwsysProcess_Execute. */
  945. static void kwsysProcessCleanup(kwsysProcess* cp, int error)
  946. {
  947. int i;
  948. if(error)
  949. {
  950. /* We are cleaning up due to an error. Report the error message
  951. if one has not been provided already. */
  952. if(cp->ErrorMessage[0] == 0)
  953. {
  954. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  955. }
  956. /* Set the error state. */
  957. cp->State = kwsysProcess_State_Error;
  958. /* Kill any children already started. */
  959. if(cp->ForkPIDs)
  960. {
  961. for(i=0; i < cp->NumberOfCommands; ++i)
  962. {
  963. if(cp->ForkPIDs[i])
  964. {
  965. kill(cp->ForkPIDs[i], SIGKILL);
  966. }
  967. }
  968. }
  969. /* Restore the working directory. */
  970. if(cp->RealWorkingDirectory)
  971. {
  972. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  973. }
  974. }
  975. /* Restore the SIGCHLD handler. */
  976. while((sigaction(SIGCHLD, &cp->OldSigChldAction, 0) < 0) &&
  977. (errno == EINTR));
  978. /* Free memory. */
  979. if(cp->ForkPIDs)
  980. {
  981. free(cp->ForkPIDs);
  982. cp->ForkPIDs = 0;
  983. }
  984. if(cp->RealWorkingDirectory)
  985. {
  986. free(cp->RealWorkingDirectory);
  987. cp->RealWorkingDirectory = 0;
  988. }
  989. /* Close pipe handles. */
  990. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  991. {
  992. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  993. }
  994. }
  995. /*--------------------------------------------------------------------------*/
  996. /* Close the given file descriptor if it is open. Reset its value to -1. */
  997. static void kwsysProcessCleanupDescriptor(int* pfd)
  998. {
  999. if(pfd && *pfd >= 0)
  1000. {
  1001. /* Keep trying to close until it is not interrupted by a
  1002. * signal. */
  1003. while((close(*pfd) < 0) && (errno == EINTR));
  1004. *pfd = -1;
  1005. }
  1006. }
  1007. /*--------------------------------------------------------------------------*/
  1008. static int kwsysProcessCreate(kwsysProcess* cp, int index,
  1009. kwsysProcessCreateInformation* si, int* readEnd)
  1010. {
  1011. /* Setup the process's stdin. */
  1012. if(index > 0)
  1013. {
  1014. si->StdIn = *readEnd;
  1015. *readEnd = 0;
  1016. }
  1017. else if(cp->PipeFileSTDIN)
  1018. {
  1019. /* Open a file for the child's stdin to read. */
  1020. si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
  1021. if(si->StdIn < 0)
  1022. {
  1023. return 0;
  1024. }
  1025. /* Set close-on-exec flag on the pipe's end. */
  1026. if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
  1027. {
  1028. return 0;
  1029. }
  1030. }
  1031. else if(cp->PipeSharedSTDIN)
  1032. {
  1033. si->StdIn = 0;
  1034. }
  1035. else
  1036. {
  1037. si->StdIn = -1;
  1038. }
  1039. /* Setup the process's stdout. */
  1040. {
  1041. /* Create the pipe. */
  1042. int p[2];
  1043. if(pipe(p) < 0)
  1044. {
  1045. return 0;
  1046. }
  1047. *readEnd = p[0];
  1048. si->StdOut = p[1];
  1049. /* Set close-on-exec flag on the pipe's ends. */
  1050. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  1051. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  1052. {
  1053. return 0;
  1054. }
  1055. }
  1056. /* Replace the stdout pipe with a file if requested. In this case
  1057. the select call will report that stdout is closed immediately. */
  1058. if(index == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
  1059. {
  1060. if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
  1061. {
  1062. return 0;
  1063. }
  1064. }
  1065. /* Replace the stdout pipe with the parent's if requested. In this
  1066. case the select call will report that stderr is closed
  1067. immediately. */
  1068. if(index == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
  1069. {
  1070. kwsysProcessCleanupDescriptor(&si->StdOut);
  1071. si->StdOut = 1;
  1072. }
  1073. /* Create the error reporting pipe. */
  1074. if(pipe(si->ErrorPipe) < 0)
  1075. {
  1076. return 0;
  1077. }
  1078. /* Set close-on-exec flag on the error pipe's write end. */
  1079. if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
  1080. {
  1081. return 0;
  1082. }
  1083. /* Fork off a child process. */
  1084. cp->ForkPIDs[index] = fork();
  1085. if(cp->ForkPIDs[index] < 0)
  1086. {
  1087. return 0;
  1088. }
  1089. if(cp->ForkPIDs[index] == 0)
  1090. {
  1091. /* Close the read end of the error reporting pipe. */
  1092. close(si->ErrorPipe[0]);
  1093. /* Setup the stdin, stdout, and stderr pipes. */
  1094. if(si->StdIn > 0)
  1095. {
  1096. dup2(si->StdIn, 0);
  1097. }
  1098. else if(si->StdIn < 0)
  1099. {
  1100. close(0);
  1101. }
  1102. if(si->StdOut != 1)
  1103. {
  1104. dup2(si->StdOut, 1);
  1105. }
  1106. if(si->StdErr != 2)
  1107. {
  1108. dup2(si->StdErr, 2);
  1109. }
  1110. /* Clear the close-on-exec flag for stdin, stdout, and stderr.
  1111. Also clear it for the termination pipe. All other pipe handles
  1112. will be closed when exec succeeds. */
  1113. fcntl(0, F_SETFD, 0);
  1114. fcntl(1, F_SETFD, 0);
  1115. fcntl(2, F_SETFD, 0);
  1116. fcntl(si->TermPipe, F_SETFD, 0);
  1117. /* Restore all default signal handlers. */
  1118. kwsysProcessRestoreDefaultSignalHandlers();
  1119. /* Execute the real process. If successful, this does not return. */
  1120. execvp(cp->Commands[index][0], cp->Commands[index]);
  1121. /* Failure. Report error to parent and terminate. */
  1122. kwsysProcessChildErrorExit(si->ErrorPipe[1]);
  1123. }
  1124. /* We are done with the error reporting pipe write end. */
  1125. kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
  1126. /* Block until the child's exec call succeeds and closes the error
  1127. pipe or writes data to the pipe to report an error. */
  1128. {
  1129. int total = 0;
  1130. int n = 1;
  1131. /* Read the entire error message up to the length of our buffer. */
  1132. while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
  1133. {
  1134. /* Keep trying to read until the operation is not interrupted. */
  1135. while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
  1136. KWSYSPE_PIPE_BUFFER_SIZE-total)) < 0) &&
  1137. (errno == EINTR));
  1138. if(n > 0)
  1139. {
  1140. total += n;
  1141. }
  1142. }
  1143. /* We are done with the error reporting pipe read end. */
  1144. kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
  1145. if(total > 0)
  1146. {
  1147. /* The child failed to execute the process. */
  1148. return 0;
  1149. }
  1150. }
  1151. /* Successfully created this child process. */
  1152. if(index > 0 || si->StdIn > 0)
  1153. {
  1154. /* The parent process does not need the input pipe read end. */
  1155. kwsysProcessCleanupDescriptor(&si->StdIn);
  1156. }
  1157. /* The parent process does not need the output pipe write ends. */
  1158. kwsysProcessCleanupDescriptor(&si->StdOut);
  1159. return 1;
  1160. }
  1161. /*--------------------------------------------------------------------------*/
  1162. static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
  1163. {
  1164. int fout;
  1165. if(!name)
  1166. {
  1167. return 1;
  1168. }
  1169. /* Close the existing descriptor. */
  1170. kwsysProcessCleanupDescriptor(p);
  1171. /* Open a file for the pipe to write (permissions 644). */
  1172. if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC,
  1173. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
  1174. {
  1175. return 0;
  1176. }
  1177. /* Set close-on-exec flag on the pipe's end. */
  1178. if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
  1179. {
  1180. return 0;
  1181. }
  1182. /* Assign the replacement descriptor. */
  1183. *p = fout;
  1184. return 1;
  1185. }
  1186. /*--------------------------------------------------------------------------*/
  1187. /* Get the time at which either the process or user timeout will
  1188. expire. Returns 1 if the user timeout is first, and 0 otherwise. */
  1189. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  1190. kwsysProcessTime* timeoutTime)
  1191. {
  1192. /* The first time this is called, we need to calculate the time at
  1193. which the child will timeout. */
  1194. if(cp->Timeout && cp->TimeoutTime.tv_sec < 0)
  1195. {
  1196. kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
  1197. cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
  1198. }
  1199. /* Start with process timeout. */
  1200. *timeoutTime = cp->TimeoutTime;
  1201. /* Check if the user timeout is earlier. */
  1202. if(userTimeout)
  1203. {
  1204. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1205. kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
  1206. kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
  1207. userTimeoutLength);
  1208. if(kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
  1209. {
  1210. *timeoutTime = userTimeoutTime;
  1211. return 1;
  1212. }
  1213. }
  1214. return 0;
  1215. }
  1216. /*--------------------------------------------------------------------------*/
  1217. /* Get the length of time before the given timeout time arrives.
  1218. Returns 1 if the time has already arrived, and 0 otherwise. */
  1219. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  1220. kwsysProcessTime* timeoutLength)
  1221. {
  1222. if(timeoutTime->tv_sec < 0)
  1223. {
  1224. /* No timeout time has been requested. */
  1225. return 0;
  1226. }
  1227. else
  1228. {
  1229. /* Calculate the remaining time. */
  1230. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1231. *timeoutLength = kwsysProcessTimeSubtract(*timeoutTime, currentTime);
  1232. if(timeoutLength->tv_sec < 0)
  1233. {
  1234. /* Timeout has already expired. */
  1235. return 1;
  1236. }
  1237. else
  1238. {
  1239. /* There is some time left. */
  1240. return 0;
  1241. }
  1242. }
  1243. }
  1244. /*--------------------------------------------------------------------------*/
  1245. static kwsysProcessTime kwsysProcessTimeGetCurrent()
  1246. {
  1247. kwsysProcessTime current;
  1248. gettimeofday(&current, 0);
  1249. return current;
  1250. }
  1251. /*--------------------------------------------------------------------------*/
  1252. static double kwsysProcessTimeToDouble(kwsysProcessTime t)
  1253. {
  1254. return (double)t.tv_sec + t.tv_usec*0.000001;
  1255. }
  1256. /*--------------------------------------------------------------------------*/
  1257. static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
  1258. {
  1259. kwsysProcessTime t;
  1260. t.tv_sec = (long)d;
  1261. t.tv_usec = (long)((d-t.tv_sec)*1000000);
  1262. return t;
  1263. }
  1264. /*--------------------------------------------------------------------------*/
  1265. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
  1266. {
  1267. return ((in1.tv_sec < in2.tv_sec) ||
  1268. ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
  1269. }
  1270. /*--------------------------------------------------------------------------*/
  1271. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
  1272. {
  1273. kwsysProcessTime out;
  1274. out.tv_sec = in1.tv_sec + in2.tv_sec;
  1275. out.tv_usec = in1.tv_usec + in2.tv_usec;
  1276. if(out.tv_usec > 1000000)
  1277. {
  1278. out.tv_usec -= 1000000;
  1279. out.tv_sec += 1;
  1280. }
  1281. return out;
  1282. }
  1283. /*--------------------------------------------------------------------------*/
  1284. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
  1285. {
  1286. kwsysProcessTime out;
  1287. out.tv_sec = in1.tv_sec - in2.tv_sec;
  1288. out.tv_usec = in1.tv_usec - in2.tv_usec;
  1289. if(out.tv_usec < 0)
  1290. {
  1291. out.tv_usec += 1000000;
  1292. out.tv_sec -= 1;
  1293. }
  1294. return out;
  1295. }
  1296. /*--------------------------------------------------------------------------*/
  1297. /* When the child process encounters an error before its program is
  1298. invoked, this is called to report the error to the parent and
  1299. exit. */
  1300. static void kwsysProcessChildErrorExit(int errorPipe)
  1301. {
  1302. /* Construct the error message. */
  1303. char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
  1304. strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1305. /* Report the error to the parent through the special pipe. */
  1306. write(errorPipe, buffer, strlen(buffer));
  1307. /* Terminate without cleanup. */
  1308. _exit(1);
  1309. }
  1310. /*--------------------------------------------------------------------------*/
  1311. /* Restores all signal handlers to their default values. */
  1312. static void kwsysProcessRestoreDefaultSignalHandlers()
  1313. {
  1314. struct sigaction act;
  1315. memset(&act, 0, sizeof(struct sigaction));
  1316. act.sa_handler = SIG_DFL;
  1317. #ifdef SIGHUP
  1318. sigaction(SIGHUP, &act, 0);
  1319. #endif
  1320. #ifdef SIGINT
  1321. sigaction(SIGINT, &act, 0);
  1322. #endif
  1323. #ifdef SIGQUIT
  1324. sigaction(SIGQUIT, &act, 0);
  1325. #endif
  1326. #ifdef SIGILL
  1327. sigaction(SIGILL, &act, 0);
  1328. #endif
  1329. #ifdef SIGTRAP
  1330. sigaction(SIGTRAP, &act, 0);
  1331. #endif
  1332. #ifdef SIGABRT
  1333. sigaction(SIGABRT, &act, 0);
  1334. #endif
  1335. #ifdef SIGIOT
  1336. sigaction(SIGIOT, &act, 0);
  1337. #endif
  1338. #ifdef SIGBUS
  1339. sigaction(SIGBUS, &act, 0);
  1340. #endif
  1341. #ifdef SIGFPE
  1342. sigaction(SIGFPE, &act, 0);
  1343. #endif
  1344. #ifdef SIGUSR1
  1345. sigaction(SIGUSR1, &act, 0);
  1346. #endif
  1347. #ifdef SIGSEGV
  1348. sigaction(SIGSEGV, &act, 0);
  1349. #endif
  1350. #ifdef SIGUSR2
  1351. sigaction(SIGUSR2, &act, 0);
  1352. #endif
  1353. #ifdef SIGPIPE
  1354. sigaction(SIGPIPE, &act, 0);
  1355. #endif
  1356. #ifdef SIGALRM
  1357. sigaction(SIGALRM, &act, 0);
  1358. #endif
  1359. #ifdef SIGTERM
  1360. sigaction(SIGTERM, &act, 0);
  1361. #endif
  1362. #ifdef SIGSTKFLT
  1363. sigaction(SIGSTKFLT, &act, 0);
  1364. #endif
  1365. #ifdef SIGCLD
  1366. sigaction(SIGCLD, &act, 0);
  1367. #endif
  1368. #ifdef SIGCHLD
  1369. sigaction(SIGCHLD, &act, 0);
  1370. #endif
  1371. #ifdef SIGCONT
  1372. sigaction(SIGCONT, &act, 0);
  1373. #endif
  1374. #ifdef SIGTSTP
  1375. sigaction(SIGTSTP, &act, 0);
  1376. #endif
  1377. #ifdef SIGTTIN
  1378. sigaction(SIGTTIN, &act, 0);
  1379. #endif
  1380. #ifdef SIGTTOU
  1381. sigaction(SIGTTOU, &act, 0);
  1382. #endif
  1383. #ifdef SIGURG
  1384. sigaction(SIGURG, &act, 0);
  1385. #endif
  1386. #ifdef SIGXCPU
  1387. sigaction(SIGXCPU, &act, 0);
  1388. #endif
  1389. #ifdef SIGXFSZ
  1390. sigaction(SIGXFSZ, &act, 0);
  1391. #endif
  1392. #ifdef SIGVTALRM
  1393. sigaction(SIGVTALRM, &act, 0);
  1394. #endif
  1395. #ifdef SIGPROF
  1396. sigaction(SIGPROF, &act, 0);
  1397. #endif
  1398. #ifdef SIGWINCH
  1399. sigaction(SIGWINCH, &act, 0);
  1400. #endif
  1401. #ifdef SIGPOLL
  1402. sigaction(SIGPOLL, &act, 0);
  1403. #endif
  1404. #ifdef SIGIO
  1405. sigaction(SIGIO, &act, 0);
  1406. #endif
  1407. #ifdef SIGPWR
  1408. sigaction(SIGPWR, &act, 0);
  1409. #endif
  1410. #ifdef SIGSYS
  1411. sigaction(SIGSYS, &act, 0);
  1412. #endif
  1413. #ifdef SIGUNUSED
  1414. sigaction(SIGUNUSED, &act, 0);
  1415. #endif
  1416. }