ProcessUNIX.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  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. # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
  1310. case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
  1311. # endif
  1312. #endif
  1313. #ifdef SIGFPE
  1314. case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
  1315. #endif
  1316. #ifdef SIGILL
  1317. case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
  1318. #endif
  1319. #ifdef SIGINT
  1320. case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
  1321. #endif
  1322. #ifdef SIGABRT
  1323. case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
  1324. #endif
  1325. #ifdef SIGKILL
  1326. case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
  1327. #endif
  1328. #ifdef SIGTERM
  1329. case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
  1330. #endif
  1331. #ifdef SIGHUP
  1332. case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
  1333. #endif
  1334. #ifdef SIGQUIT
  1335. case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
  1336. #endif
  1337. #ifdef SIGTRAP
  1338. case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
  1339. #endif
  1340. #ifdef SIGIOT
  1341. # if !defined(SIGABRT) || SIGIOT != SIGABRT
  1342. case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
  1343. # endif
  1344. #endif
  1345. #ifdef SIGUSR1
  1346. case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
  1347. #endif
  1348. #ifdef SIGUSR2
  1349. case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
  1350. #endif
  1351. #ifdef SIGPIPE
  1352. case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
  1353. #endif
  1354. #ifdef SIGALRM
  1355. case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
  1356. #endif
  1357. #ifdef SIGSTKFLT
  1358. case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
  1359. #endif
  1360. #ifdef SIGCHLD
  1361. case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
  1362. #elif defined(SIGCLD)
  1363. case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
  1364. #endif
  1365. #ifdef SIGCONT
  1366. case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
  1367. #endif
  1368. #ifdef SIGSTOP
  1369. case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
  1370. #endif
  1371. #ifdef SIGTSTP
  1372. case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
  1373. #endif
  1374. #ifdef SIGTTIN
  1375. case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
  1376. #endif
  1377. #ifdef SIGTTOU
  1378. case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
  1379. #endif
  1380. #ifdef SIGURG
  1381. case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
  1382. #endif
  1383. #ifdef SIGXCPU
  1384. case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
  1385. #endif
  1386. #ifdef SIGXFSZ
  1387. case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
  1388. #endif
  1389. #ifdef SIGVTALRM
  1390. case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
  1391. #endif
  1392. #ifdef SIGPROF
  1393. case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
  1394. #endif
  1395. #ifdef SIGWINCH
  1396. case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
  1397. #endif
  1398. #ifdef SIGPOLL
  1399. case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
  1400. #endif
  1401. #ifdef SIGIO
  1402. # if !defined(SIGPOLL) || SIGIO != SIGPOLL
  1403. case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
  1404. # endif
  1405. #endif
  1406. #ifdef SIGPWR
  1407. case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
  1408. #endif
  1409. #ifdef SIGSYS
  1410. case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
  1411. #endif
  1412. #ifdef SIGUNUSED
  1413. # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
  1414. case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
  1415. # endif
  1416. #endif
  1417. default:
  1418. cp->ExitException = kwsysProcess_Exception_Other;
  1419. sprintf(cp->ExitExceptionString, "Signal %d", sig);
  1420. break;
  1421. }
  1422. }
  1423. #undef KWSYSPE_CASE
  1424. /*--------------------------------------------------------------------------*/
  1425. /* When the child process encounters an error before its program is
  1426. invoked, this is called to report the error to the parent and
  1427. exit. */
  1428. static void kwsysProcessChildErrorExit(int errorPipe)
  1429. {
  1430. /* Construct the error message. */
  1431. char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
  1432. strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1433. /* Report the error to the parent through the special pipe. */
  1434. write(errorPipe, buffer, strlen(buffer));
  1435. /* Terminate without cleanup. */
  1436. _exit(1);
  1437. }
  1438. /*--------------------------------------------------------------------------*/
  1439. /* Restores all signal handlers to their default values. */
  1440. static void kwsysProcessRestoreDefaultSignalHandlers(void)
  1441. {
  1442. struct sigaction act;
  1443. memset(&act, 0, sizeof(struct sigaction));
  1444. act.sa_handler = SIG_DFL;
  1445. #ifdef SIGHUP
  1446. sigaction(SIGHUP, &act, 0);
  1447. #endif
  1448. #ifdef SIGINT
  1449. sigaction(SIGINT, &act, 0);
  1450. #endif
  1451. #ifdef SIGQUIT
  1452. sigaction(SIGQUIT, &act, 0);
  1453. #endif
  1454. #ifdef SIGILL
  1455. sigaction(SIGILL, &act, 0);
  1456. #endif
  1457. #ifdef SIGTRAP
  1458. sigaction(SIGTRAP, &act, 0);
  1459. #endif
  1460. #ifdef SIGABRT
  1461. sigaction(SIGABRT, &act, 0);
  1462. #endif
  1463. #ifdef SIGIOT
  1464. sigaction(SIGIOT, &act, 0);
  1465. #endif
  1466. #ifdef SIGBUS
  1467. sigaction(SIGBUS, &act, 0);
  1468. #endif
  1469. #ifdef SIGFPE
  1470. sigaction(SIGFPE, &act, 0);
  1471. #endif
  1472. #ifdef SIGUSR1
  1473. sigaction(SIGUSR1, &act, 0);
  1474. #endif
  1475. #ifdef SIGSEGV
  1476. sigaction(SIGSEGV, &act, 0);
  1477. #endif
  1478. #ifdef SIGUSR2
  1479. sigaction(SIGUSR2, &act, 0);
  1480. #endif
  1481. #ifdef SIGPIPE
  1482. sigaction(SIGPIPE, &act, 0);
  1483. #endif
  1484. #ifdef SIGALRM
  1485. sigaction(SIGALRM, &act, 0);
  1486. #endif
  1487. #ifdef SIGTERM
  1488. sigaction(SIGTERM, &act, 0);
  1489. #endif
  1490. #ifdef SIGSTKFLT
  1491. sigaction(SIGSTKFLT, &act, 0);
  1492. #endif
  1493. #ifdef SIGCLD
  1494. sigaction(SIGCLD, &act, 0);
  1495. #endif
  1496. #ifdef SIGCHLD
  1497. sigaction(SIGCHLD, &act, 0);
  1498. #endif
  1499. #ifdef SIGCONT
  1500. sigaction(SIGCONT, &act, 0);
  1501. #endif
  1502. #ifdef SIGTSTP
  1503. sigaction(SIGTSTP, &act, 0);
  1504. #endif
  1505. #ifdef SIGTTIN
  1506. sigaction(SIGTTIN, &act, 0);
  1507. #endif
  1508. #ifdef SIGTTOU
  1509. sigaction(SIGTTOU, &act, 0);
  1510. #endif
  1511. #ifdef SIGURG
  1512. sigaction(SIGURG, &act, 0);
  1513. #endif
  1514. #ifdef SIGXCPU
  1515. sigaction(SIGXCPU, &act, 0);
  1516. #endif
  1517. #ifdef SIGXFSZ
  1518. sigaction(SIGXFSZ, &act, 0);
  1519. #endif
  1520. #ifdef SIGVTALRM
  1521. sigaction(SIGVTALRM, &act, 0);
  1522. #endif
  1523. #ifdef SIGPROF
  1524. sigaction(SIGPROF, &act, 0);
  1525. #endif
  1526. #ifdef SIGWINCH
  1527. sigaction(SIGWINCH, &act, 0);
  1528. #endif
  1529. #ifdef SIGPOLL
  1530. sigaction(SIGPOLL, &act, 0);
  1531. #endif
  1532. #ifdef SIGIO
  1533. sigaction(SIGIO, &act, 0);
  1534. #endif
  1535. #ifdef SIGPWR
  1536. sigaction(SIGPWR, &act, 0);
  1537. #endif
  1538. #ifdef SIGSYS
  1539. sigaction(SIGSYS, &act, 0);
  1540. #endif
  1541. #ifdef SIGUNUSED
  1542. sigaction(SIGUNUSED, &act, 0);
  1543. #endif
  1544. }