ProcessUNIX.c 45 KB

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