ProcessUNIX.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  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. #include "kwsysPrivate.h"
  11. #include KWSYS_HEADER(Process.h)
  12. /* Work-around CMake dependency scanning limitation. This must
  13. duplicate the above list of headers. */
  14. #if 0
  15. # include "Process.h.in"
  16. #endif
  17. /*
  18. Implementation for UNIX
  19. On UNIX, a child process is forked to exec the program. Three
  20. output pipes from the child are read by the parent process using a
  21. select call to block until data are ready. Two of the pipes are
  22. stdout and stderr for the child. The third is a special error pipe
  23. that has two purposes. First, if the child cannot exec the program,
  24. the error is reported through the error pipe. Second, the error
  25. pipe is left open until the child exits. This is used in
  26. conjunction with the timeout on the select call to implement a
  27. timeout for program even when it closes stdout and stderr.
  28. */
  29. /*
  30. TODO:
  31. We cannot create the pipeline of processes in suspended states. How
  32. do we cleanup processes already started when one fails to load? Right
  33. now we are just killing them, which is probably not the right thing to
  34. do.
  35. */
  36. #include <stdio.h> /* snprintf */
  37. #include <stdlib.h> /* malloc, free */
  38. #include <string.h> /* strdup, strerror, memset */
  39. #include <sys/time.h> /* struct timeval */
  40. #include <sys/types.h> /* pid_t, fd_set */
  41. #include <sys/wait.h> /* waitpid */
  42. #include <sys/stat.h> /* open mode */
  43. #include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
  44. #include <fcntl.h> /* fcntl */
  45. #include <errno.h> /* errno */
  46. #include <time.h> /* gettimeofday */
  47. #include <signal.h> /* sigaction */
  48. #include <dirent.h> /* DIR, dirent */
  49. /* The number of pipes for the child's output. The standard stdout
  50. and stderr pipes are the first two. One more pipe is used to
  51. detect when the child process has terminated. The third pipe is
  52. not given to the child process, so it cannot close it until it
  53. terminates. */
  54. #define KWSYSPE_PIPE_COUNT 3
  55. #define KWSYSPE_PIPE_STDOUT 0
  56. #define KWSYSPE_PIPE_STDERR 1
  57. #define KWSYSPE_PIPE_TERM 2
  58. /* The maximum amount to read from a pipe at a time. */
  59. #define KWSYSPE_PIPE_BUFFER_SIZE 1024
  60. /* Keep track of times using a signed representation. Switch to the
  61. native (possibly unsigned) representation only when calling native
  62. functions. */
  63. typedef struct timeval kwsysProcessTimeNative;
  64. typedef struct kwsysProcessTime_s kwsysProcessTime;
  65. struct kwsysProcessTime_s
  66. {
  67. long tv_sec;
  68. long tv_usec;
  69. };
  70. typedef struct kwsysProcessCreateInformation_s
  71. {
  72. int StdIn;
  73. int StdOut;
  74. int StdErr;
  75. int TermPipe;
  76. int ErrorPipe[2];
  77. } kwsysProcessCreateInformation;
  78. /*--------------------------------------------------------------------------*/
  79. static int kwsysProcessInitialize(kwsysProcess* cp);
  80. static void kwsysProcessCleanup(kwsysProcess* cp, int error);
  81. static void kwsysProcessCleanupDescriptor(int* pfd);
  82. static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
  83. kwsysProcessCreateInformation* si, int* readEnd);
  84. static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
  85. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  86. kwsysProcessTime* timeoutTime);
  87. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  88. double* userTimeout,
  89. kwsysProcessTimeNative* timeoutLength);
  90. static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
  91. static double kwsysProcessTimeToDouble(kwsysProcessTime t);
  92. static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
  93. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
  94. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
  95. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
  96. static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
  97. static void kwsysProcessChildErrorExit(int errorPipe);
  98. static void kwsysProcessRestoreDefaultSignalHandlers(void);
  99. static pid_t kwsysProcessFork(kwsysProcess* cp,
  100. kwsysProcessCreateInformation* si);
  101. static void kwsysProcessKill(pid_t process_id);
  102. /*--------------------------------------------------------------------------*/
  103. /* Structure containing data used to implement the child's execution. */
  104. struct kwsysProcess_s
  105. {
  106. /* The command lines to execute. */
  107. char*** Commands;
  108. int NumberOfCommands;
  109. /* Descriptors for the read ends of the child's output pipes. */
  110. int PipeReadEnds[KWSYSPE_PIPE_COUNT];
  111. /* Buffer for pipe data. */
  112. char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
  113. /* Process IDs returned by the calls to fork. */
  114. pid_t* ForkPIDs;
  115. /* Flag for whether the children were terminated by a faild select. */
  116. int SelectError;
  117. /* The timeout length. */
  118. double Timeout;
  119. /* The working directory for the process. */
  120. char* WorkingDirectory;
  121. /* Whether to create the child as a detached process. */
  122. int OptionDetach;
  123. /* Whether the child was created as a detached process. */
  124. int Detached;
  125. /* Time at which the child started. Negative for no timeout. */
  126. kwsysProcessTime StartTime;
  127. /* Time at which the child will timeout. Negative for no timeout. */
  128. kwsysProcessTime TimeoutTime;
  129. /* Flag for whether the timeout expired. */
  130. int TimeoutExpired;
  131. /* The old SIGCHLD handler. */
  132. struct sigaction OldSigChldAction;
  133. /* The number of pipes left open during execution. */
  134. int PipesLeft;
  135. /* File descriptor set for call to select. */
  136. fd_set PipeSet;
  137. /* The current status of the child process. */
  138. int State;
  139. /* The exceptional behavior that terminated the child process, if
  140. * any. */
  141. int ExitException;
  142. /* The exit code of the child process. */
  143. int ExitCode;
  144. /* The exit value of the child process, if any. */
  145. int ExitValue;
  146. /* Whether the process was killed. */
  147. int Killed;
  148. /* Buffer for error message in case of failure. */
  149. char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
  150. /* Description for the ExitException. */
  151. char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
  152. /* The exit codes of each child process in the pipeline. */
  153. int* CommandExitCodes;
  154. /* Name of files to which stdin and stdout pipes are attached. */
  155. char* PipeFileSTDIN;
  156. char* PipeFileSTDOUT;
  157. char* PipeFileSTDERR;
  158. /* Whether each pipe is shared with the parent process. */
  159. int PipeSharedSTDIN;
  160. int PipeSharedSTDOUT;
  161. int PipeSharedSTDERR;
  162. /* The real working directory of this process. */
  163. int RealWorkingDirectoryLength;
  164. char* RealWorkingDirectory;
  165. };
  166. /*--------------------------------------------------------------------------*/
  167. kwsysProcess* kwsysProcess_New(void)
  168. {
  169. /* Allocate a process control structure. */
  170. kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
  171. if(!cp)
  172. {
  173. return 0;
  174. }
  175. memset(cp, 0, sizeof(kwsysProcess));
  176. /* Share stdin with the parent process by default. */
  177. cp->PipeSharedSTDIN = 1;
  178. /* Set initial status. */
  179. cp->State = kwsysProcess_State_Starting;
  180. return cp;
  181. }
  182. /*--------------------------------------------------------------------------*/
  183. void kwsysProcess_Delete(kwsysProcess* cp)
  184. {
  185. /* Make sure we have an instance. */
  186. if(!cp)
  187. {
  188. return;
  189. }
  190. /* If the process is executing, wait for it to finish. */
  191. if(cp->State == kwsysProcess_State_Executing)
  192. {
  193. if(cp->Detached)
  194. {
  195. kwsysProcess_Disown(cp);
  196. }
  197. else
  198. {
  199. kwsysProcess_WaitForExit(cp, 0);
  200. }
  201. }
  202. /* Free memory. */
  203. kwsysProcess_SetCommand(cp, 0);
  204. kwsysProcess_SetWorkingDirectory(cp, 0);
  205. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
  206. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
  207. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
  208. if(cp->CommandExitCodes)
  209. {
  210. free(cp->CommandExitCodes);
  211. }
  212. free(cp);
  213. }
  214. /*--------------------------------------------------------------------------*/
  215. int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
  216. {
  217. int i;
  218. if(!cp)
  219. {
  220. return 0;
  221. }
  222. for(i=0; i < cp->NumberOfCommands; ++i)
  223. {
  224. char** c = cp->Commands[i];
  225. while(*c)
  226. {
  227. free(*c++);
  228. }
  229. free(cp->Commands[i]);
  230. }
  231. cp->NumberOfCommands = 0;
  232. if(cp->Commands)
  233. {
  234. free(cp->Commands);
  235. cp->Commands = 0;
  236. }
  237. if(command)
  238. {
  239. return kwsysProcess_AddCommand(cp, command);
  240. }
  241. return 1;
  242. }
  243. /*--------------------------------------------------------------------------*/
  244. int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
  245. {
  246. int newNumberOfCommands;
  247. char*** newCommands;
  248. /* Make sure we have a command to add. */
  249. if(!cp || !command)
  250. {
  251. return 0;
  252. }
  253. /* Allocate a new array for command pointers. */
  254. newNumberOfCommands = cp->NumberOfCommands + 1;
  255. if(!(newCommands = (char***)malloc(sizeof(char**) * newNumberOfCommands)))
  256. {
  257. /* Out of memory. */
  258. return 0;
  259. }
  260. /* Copy any existing commands into the new array. */
  261. {
  262. int i;
  263. for(i=0; i < cp->NumberOfCommands; ++i)
  264. {
  265. newCommands[i] = cp->Commands[i];
  266. }
  267. }
  268. /* Add the new command. */
  269. {
  270. char const* const* c = command;
  271. int n = 0;
  272. int i = 0;
  273. while(*c++);
  274. n = c - command - 1;
  275. newCommands[cp->NumberOfCommands] = (char**)malloc((n+1)*sizeof(char*));
  276. if(!newCommands[cp->NumberOfCommands])
  277. {
  278. /* Out of memory. */
  279. free(newCommands);
  280. return 0;
  281. }
  282. for(i=0; i < n; ++i)
  283. {
  284. newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
  285. if(!newCommands[cp->NumberOfCommands][i])
  286. {
  287. break;
  288. }
  289. }
  290. if(i < n)
  291. {
  292. /* Out of memory. */
  293. for(;i > 0; --i)
  294. {
  295. free(newCommands[cp->NumberOfCommands][i-1]);
  296. }
  297. free(newCommands);
  298. return 0;
  299. }
  300. newCommands[cp->NumberOfCommands][n] = 0;
  301. }
  302. /* Successfully allocated new command array. Free the old array. */
  303. free(cp->Commands);
  304. cp->Commands = newCommands;
  305. cp->NumberOfCommands = newNumberOfCommands;
  306. return 1;
  307. }
  308. /*--------------------------------------------------------------------------*/
  309. void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
  310. {
  311. if(!cp)
  312. {
  313. return;
  314. }
  315. cp->Timeout = timeout;
  316. if(cp->Timeout < 0)
  317. {
  318. cp->Timeout = 0;
  319. }
  320. }
  321. /*--------------------------------------------------------------------------*/
  322. int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
  323. {
  324. if(!cp)
  325. {
  326. return 0;
  327. }
  328. if(cp->WorkingDirectory == dir)
  329. {
  330. return 1;
  331. }
  332. if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
  333. {
  334. return 1;
  335. }
  336. if(cp->WorkingDirectory)
  337. {
  338. free(cp->WorkingDirectory);
  339. cp->WorkingDirectory = 0;
  340. }
  341. if(dir)
  342. {
  343. cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
  344. if(!cp->WorkingDirectory)
  345. {
  346. return 0;
  347. }
  348. strcpy(cp->WorkingDirectory, dir);
  349. }
  350. return 1;
  351. }
  352. /*--------------------------------------------------------------------------*/
  353. int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
  354. {
  355. char** pfile;
  356. if(!cp)
  357. {
  358. return 0;
  359. }
  360. switch(prPipe)
  361. {
  362. case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
  363. case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
  364. case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
  365. default: return 0;
  366. }
  367. if(*pfile)
  368. {
  369. free(*pfile);
  370. *pfile = 0;
  371. }
  372. if(file)
  373. {
  374. *pfile = malloc(strlen(file)+1);
  375. if(!*pfile)
  376. {
  377. return 0;
  378. }
  379. strcpy(*pfile, file);
  380. }
  381. /* If we are redirecting the pipe, do not share it. */
  382. if(*pfile)
  383. {
  384. kwsysProcess_SetPipeShared(cp, prPipe, 0);
  385. }
  386. return 1;
  387. }
  388. /*--------------------------------------------------------------------------*/
  389. void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
  390. {
  391. if(!cp)
  392. {
  393. return;
  394. }
  395. switch(prPipe)
  396. {
  397. case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
  398. case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
  399. case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
  400. default: return;
  401. }
  402. /* If we are sharing the pipe, do not redirect it to a file. */
  403. if(shared)
  404. {
  405. kwsysProcess_SetPipeFile(cp, prPipe, 0);
  406. }
  407. }
  408. /*--------------------------------------------------------------------------*/
  409. int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
  410. {
  411. if(!cp)
  412. {
  413. return 0;
  414. }
  415. switch(optionId)
  416. {
  417. case kwsysProcess_Option_Detach: return cp->OptionDetach;
  418. default: return 0;
  419. }
  420. }
  421. /*--------------------------------------------------------------------------*/
  422. void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
  423. {
  424. if(!cp)
  425. {
  426. return;
  427. }
  428. switch(optionId)
  429. {
  430. case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
  431. default: break;
  432. }
  433. }
  434. /*--------------------------------------------------------------------------*/
  435. int kwsysProcess_GetState(kwsysProcess* cp)
  436. {
  437. return cp? cp->State : kwsysProcess_State_Error;
  438. }
  439. /*--------------------------------------------------------------------------*/
  440. int kwsysProcess_GetExitException(kwsysProcess* cp)
  441. {
  442. return cp? cp->ExitException : kwsysProcess_Exception_Other;
  443. }
  444. /*--------------------------------------------------------------------------*/
  445. int kwsysProcess_GetExitCode(kwsysProcess* cp)
  446. {
  447. return cp? cp->ExitCode : 0;
  448. }
  449. /*--------------------------------------------------------------------------*/
  450. int kwsysProcess_GetExitValue(kwsysProcess* cp)
  451. {
  452. return cp? cp->ExitValue : -1;
  453. }
  454. /*--------------------------------------------------------------------------*/
  455. const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
  456. {
  457. if(!cp)
  458. {
  459. return "Process management structure could not be allocated";
  460. }
  461. else if(cp->State == kwsysProcess_State_Error)
  462. {
  463. return cp->ErrorMessage;
  464. }
  465. return "Success";
  466. }
  467. /*--------------------------------------------------------------------------*/
  468. const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
  469. {
  470. if(!cp)
  471. {
  472. return "GetExceptionString called with NULL process management structure";
  473. }
  474. else if(cp->State == kwsysProcess_State_Exception)
  475. {
  476. return cp->ExitExceptionString;
  477. }
  478. return "No exception";
  479. }
  480. /*--------------------------------------------------------------------------*/
  481. void kwsysProcess_Execute(kwsysProcess* cp)
  482. {
  483. int i;
  484. struct sigaction newSigChldAction;
  485. kwsysProcessCreateInformation si = {-1, -1, -1, -1, {-1, -1}};
  486. /* Do not execute a second copy simultaneously. */
  487. if(!cp || cp->State == kwsysProcess_State_Executing)
  488. {
  489. return;
  490. }
  491. /* Initialize the control structure for a new process. */
  492. if(!kwsysProcessInitialize(cp))
  493. {
  494. strcpy(cp->ErrorMessage, "Out of memory");
  495. cp->State = kwsysProcess_State_Error;
  496. return;
  497. }
  498. /* Save the real working directory of this process and change to
  499. the working directory for the child processes. This is needed
  500. to make pipe file paths evaluate correctly. */
  501. if(cp->WorkingDirectory)
  502. {
  503. int r;
  504. if(!getcwd(cp->RealWorkingDirectory, cp->RealWorkingDirectoryLength))
  505. {
  506. kwsysProcessCleanup(cp, 1);
  507. return;
  508. }
  509. /* Some platforms specify that the chdir call may be
  510. interrupted. Repeat the call until it finishes. */
  511. while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
  512. if(r < 0)
  513. {
  514. kwsysProcessCleanup(cp, 1);
  515. return;
  516. }
  517. }
  518. /* We want no special handling of SIGCHLD. Repeat call until it is
  519. not interrupted. */
  520. memset(&newSigChldAction, 0, sizeof(struct sigaction));
  521. newSigChldAction.sa_handler = SIG_DFL;
  522. while((sigaction(SIGCHLD, &newSigChldAction, &cp->OldSigChldAction) < 0) &&
  523. (errno == EINTR));
  524. /* Setup the stderr and termination pipes to be shared by all processes. */
  525. for(i=KWSYSPE_PIPE_STDERR; i < KWSYSPE_PIPE_COUNT; ++i)
  526. {
  527. /* Create the pipe. */
  528. int p[2];
  529. if(pipe(p) < 0)
  530. {
  531. kwsysProcessCleanup(cp, 1);
  532. return;
  533. }
  534. /* Store the pipe. */
  535. cp->PipeReadEnds[i] = p[0];
  536. if(i == KWSYSPE_PIPE_STDERR)
  537. {
  538. si.StdErr = p[1];
  539. }
  540. else
  541. {
  542. si.TermPipe = p[1];
  543. }
  544. /* Set close-on-exec flag on the pipe's ends. */
  545. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  546. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  547. {
  548. kwsysProcessCleanup(cp, 1);
  549. kwsysProcessCleanupDescriptor(&si.StdErr);
  550. kwsysProcessCleanupDescriptor(&si.TermPipe);
  551. return;
  552. }
  553. }
  554. /* Replace the stderr pipe with a file if requested. In this case
  555. the select call will report that stderr is closed immediately. */
  556. if(cp->PipeFileSTDERR)
  557. {
  558. if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
  559. {
  560. kwsysProcessCleanup(cp, 1);
  561. kwsysProcessCleanupDescriptor(&si.StdErr);
  562. kwsysProcessCleanupDescriptor(&si.TermPipe);
  563. return;
  564. }
  565. }
  566. /* Replace the stderr pipe with the parent's if requested. In this
  567. case the select call will report that stderr is closed
  568. immediately. */
  569. if(cp->PipeSharedSTDERR)
  570. {
  571. kwsysProcessCleanupDescriptor(&si.StdErr);
  572. si.StdErr = 2;
  573. }
  574. /* The timeout period starts now. */
  575. cp->StartTime = kwsysProcessTimeGetCurrent();
  576. cp->TimeoutTime.tv_sec = -1;
  577. cp->TimeoutTime.tv_usec = -1;
  578. /* Create the pipeline of processes. */
  579. {
  580. int readEnd = -1;
  581. for(i=0; i < cp->NumberOfCommands; ++i)
  582. {
  583. if(!kwsysProcessCreate(cp, i, &si, &readEnd))
  584. {
  585. kwsysProcessCleanup(cp, 1);
  586. /* Release resources that may have been allocated for this
  587. process before an error occurred. */
  588. kwsysProcessCleanupDescriptor(&readEnd);
  589. if(si.StdIn != 0)
  590. {
  591. kwsysProcessCleanupDescriptor(&si.StdIn);
  592. }
  593. if(si.StdOut != 1)
  594. {
  595. kwsysProcessCleanupDescriptor(&si.StdOut);
  596. }
  597. if(si.StdErr != 2)
  598. {
  599. kwsysProcessCleanupDescriptor(&si.StdErr);
  600. }
  601. kwsysProcessCleanupDescriptor(&si.TermPipe);
  602. kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
  603. kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
  604. return;
  605. }
  606. }
  607. /* Save a handle to the output pipe for the last process. */
  608. cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
  609. }
  610. /* The parent process does not need the output pipe write ends. */
  611. if(si.StdErr != 2)
  612. {
  613. kwsysProcessCleanupDescriptor(&si.StdErr);
  614. }
  615. kwsysProcessCleanupDescriptor(&si.TermPipe);
  616. /* Restore the working directory. */
  617. if(cp->RealWorkingDirectory)
  618. {
  619. /* Some platforms specify that the chdir call may be
  620. interrupted. Repeat the call until it finishes. */
  621. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  622. free(cp->RealWorkingDirectory);
  623. cp->RealWorkingDirectory = 0;
  624. }
  625. /* All the pipes are now open. */
  626. cp->PipesLeft = KWSYSPE_PIPE_COUNT;
  627. /* The process has now started. */
  628. cp->State = kwsysProcess_State_Executing;
  629. cp->Detached = cp->OptionDetach;
  630. }
  631. /*--------------------------------------------------------------------------*/
  632. kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
  633. {
  634. int i;
  635. /* Make sure a detached child process is running. */
  636. if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
  637. cp->TimeoutExpired || cp->Killed)
  638. {
  639. return;
  640. }
  641. /* Close any pipes that are still open. */
  642. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  643. {
  644. if(cp->PipeReadEnds[i] >= 0)
  645. {
  646. /* If the pipe was reported by the last call to select, we must
  647. read from it. Ignore the data. */
  648. if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  649. {
  650. /* We are handling this pipe now. Remove it from the set. */
  651. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  652. /* The pipe is ready to read without blocking. Keep trying to
  653. read until the operation is not interrupted. */
  654. while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
  655. KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
  656. }
  657. /* We are done reading from this pipe. */
  658. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  659. --cp->PipesLeft;
  660. }
  661. }
  662. /* We will not wait for exit, so cleanup now. */
  663. kwsysProcessCleanup(cp, 0);
  664. /* The process has been disowned. */
  665. cp->State = kwsysProcess_State_Disowned;
  666. }
  667. /*--------------------------------------------------------------------------*/
  668. int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
  669. double* userTimeout)
  670. {
  671. int i;
  672. int max = -1;
  673. kwsysProcessTimeNative* timeout = 0;
  674. kwsysProcessTimeNative timeoutLength;
  675. kwsysProcessTime timeoutTime;
  676. kwsysProcessTime userStartTime = {0, 0};
  677. int user = 0;
  678. int expired = 0;
  679. int pipeId = kwsysProcess_Pipe_None;
  680. int numReady = 0;
  681. /* Make sure we are executing a process. */
  682. if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
  683. cp->TimeoutExpired)
  684. {
  685. return kwsysProcess_Pipe_None;
  686. }
  687. /* Record the time at which user timeout period starts. */
  688. if(userTimeout)
  689. {
  690. userStartTime = kwsysProcessTimeGetCurrent();
  691. }
  692. /* Calculate the time at which a timeout will expire, and whether it
  693. is the user or process timeout. */
  694. user = kwsysProcessGetTimeoutTime(cp, userTimeout, &timeoutTime);
  695. /* Data can only be available when pipes are open. If the process
  696. is not running, cp->PipesLeft will be 0. */
  697. while(cp->PipesLeft > 0)
  698. {
  699. /* Check for any open pipes with data reported ready by the last
  700. call to select. According to "man select_tut" we must deal
  701. with all descriptors reported by a call to select before
  702. passing them to another select call. */
  703. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  704. {
  705. if(cp->PipeReadEnds[i] >= 0 &&
  706. FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  707. {
  708. int n;
  709. /* We are handling this pipe now. Remove it from the set. */
  710. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  711. /* The pipe is ready to read without blocking. Keep trying to
  712. read until the operation is not interrupted. */
  713. while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
  714. KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
  715. if(n > 0)
  716. {
  717. /* We have data on this pipe. */
  718. if(i == KWSYSPE_PIPE_TERM)
  719. {
  720. /* This is data on the special termination pipe. Ignore it. */
  721. }
  722. else if(data && length)
  723. {
  724. /* Report this data. */
  725. *data = cp->PipeBuffer;
  726. *length = n;
  727. switch(i)
  728. {
  729. case KWSYSPE_PIPE_STDOUT:
  730. pipeId = kwsysProcess_Pipe_STDOUT; break;
  731. case KWSYSPE_PIPE_STDERR:
  732. pipeId = kwsysProcess_Pipe_STDERR; break;
  733. };
  734. break;
  735. }
  736. }
  737. else
  738. {
  739. /* We are done reading from this pipe. */
  740. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  741. --cp->PipesLeft;
  742. }
  743. }
  744. }
  745. /* If we have data, break early. */
  746. if(pipeId)
  747. {
  748. break;
  749. }
  750. /* Make sure the set is empty (it should always be empty here
  751. anyway). */
  752. FD_ZERO(&cp->PipeSet);
  753. /* Setup a timeout if required. */
  754. if(timeoutTime.tv_sec < 0)
  755. {
  756. timeout = 0;
  757. }
  758. else
  759. {
  760. timeout = &timeoutLength;
  761. }
  762. if(kwsysProcessGetTimeoutLeft(&timeoutTime, user?userTimeout:0, &timeoutLength))
  763. {
  764. /* Timeout has already expired. */
  765. expired = 1;
  766. break;
  767. }
  768. /* Add the pipe reading ends that are still open. */
  769. max = -1;
  770. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  771. {
  772. if(cp->PipeReadEnds[i] >= 0)
  773. {
  774. FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
  775. if(cp->PipeReadEnds[i] > max)
  776. {
  777. max = cp->PipeReadEnds[i];
  778. }
  779. }
  780. }
  781. /* Make sure we have a non-empty set. */
  782. if(max < 0)
  783. {
  784. /* All pipes have closed. Child has terminated. */
  785. break;
  786. }
  787. /* Run select to block until data are available. Repeat call
  788. until it is not interrupted. */
  789. while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
  790. (errno == EINTR));
  791. /* Check result of select. */
  792. if(numReady == 0)
  793. {
  794. /* Select's timeout expired. */
  795. expired = 1;
  796. break;
  797. }
  798. else if(numReady < 0)
  799. {
  800. /* Select returned an error. Leave the error description in the
  801. pipe buffer. */
  802. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  803. /* Kill the children now. */
  804. kwsysProcess_Kill(cp);
  805. cp->Killed = 0;
  806. cp->SelectError = 1;
  807. }
  808. }
  809. /* Update the user timeout. */
  810. if(userTimeout)
  811. {
  812. kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
  813. kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
  814. userStartTime);
  815. double d = kwsysProcessTimeToDouble(difference);
  816. *userTimeout -= d;
  817. if(*userTimeout < 0)
  818. {
  819. *userTimeout = 0;
  820. }
  821. }
  822. /* Check what happened. */
  823. if(pipeId)
  824. {
  825. /* Data are ready on a pipe. */
  826. return pipeId;
  827. }
  828. else if(expired)
  829. {
  830. /* A timeout has expired. */
  831. if(user)
  832. {
  833. /* The user timeout has expired. It has no time left. */
  834. return kwsysProcess_Pipe_Timeout;
  835. }
  836. else
  837. {
  838. /* The process timeout has expired. Kill the children now. */
  839. kwsysProcess_Kill(cp);
  840. cp->Killed = 0;
  841. cp->TimeoutExpired = 1;
  842. return kwsysProcess_Pipe_None;
  843. }
  844. }
  845. else
  846. {
  847. /* No pipes are left open. */
  848. return kwsysProcess_Pipe_None;
  849. }
  850. }
  851. /*--------------------------------------------------------------------------*/
  852. int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
  853. {
  854. int result = 0;
  855. int status = 0;
  856. int prPipe = 0;
  857. /* Make sure we are executing a process. */
  858. if(!cp || cp->State != kwsysProcess_State_Executing)
  859. {
  860. return 1;
  861. }
  862. /* Wait for all the pipes to close. Ignore all data. */
  863. while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
  864. {
  865. if(prPipe == kwsysProcess_Pipe_Timeout)
  866. {
  867. return 0;
  868. }
  869. }
  870. /* Wait for each child to terminate. The process should have
  871. already exited because KWSYSPE_PIPE_TERM has been closed by this
  872. point. Repeat the call until it is not interrupted. */
  873. if(!cp->Detached)
  874. {
  875. int i;
  876. for(i=0; i < cp->NumberOfCommands; ++i)
  877. {
  878. while(((result = waitpid(cp->ForkPIDs[i],
  879. &cp->CommandExitCodes[i], 0)) < 0) &&
  880. (errno == EINTR));
  881. if(result <= 0 && cp->State != kwsysProcess_State_Error)
  882. {
  883. /* Unexpected error. Report the first time this happens. */
  884. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  885. cp->State = kwsysProcess_State_Error;
  886. }
  887. }
  888. }
  889. /* Check if there was an error in one of the waitpid calls. */
  890. if(cp->State == kwsysProcess_State_Error)
  891. {
  892. /* The error message is already in its buffer. Tell
  893. kwsysProcessCleanup to not create it. */
  894. kwsysProcessCleanup(cp, 0);
  895. return 1;
  896. }
  897. /* Check whether the child reported an error invoking the process. */
  898. if(cp->SelectError)
  899. {
  900. /* The error message is already in its buffer. Tell
  901. kwsysProcessCleanup to not create it. */
  902. kwsysProcessCleanup(cp, 0);
  903. cp->State = kwsysProcess_State_Error;
  904. return 1;
  905. }
  906. /* Use the status of the last process in the pipeline. */
  907. status = cp->CommandExitCodes[cp->NumberOfCommands-1];
  908. /* Determine the outcome. */
  909. if(cp->Killed)
  910. {
  911. /* We killed the child. */
  912. cp->State = kwsysProcess_State_Killed;
  913. }
  914. else if(cp->TimeoutExpired)
  915. {
  916. /* The timeout expired. */
  917. cp->State = kwsysProcess_State_Expired;
  918. }
  919. else if(WIFEXITED(status))
  920. {
  921. /* The child exited normally. */
  922. cp->State = kwsysProcess_State_Exited;
  923. cp->ExitException = kwsysProcess_Exception_None;
  924. cp->ExitCode = status;
  925. cp->ExitValue = (int)WEXITSTATUS(status);
  926. }
  927. else if(WIFSIGNALED(status))
  928. {
  929. /* The child received an unhandled signal. */
  930. cp->State = kwsysProcess_State_Exception;
  931. cp->ExitCode = status;
  932. kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
  933. }
  934. else
  935. {
  936. /* Error getting the child return code. */
  937. strcpy(cp->ErrorMessage, "Error getting child return code.");
  938. cp->State = kwsysProcess_State_Error;
  939. }
  940. /* Normal cleanup. */
  941. kwsysProcessCleanup(cp, 0);
  942. return 1;
  943. }
  944. /*--------------------------------------------------------------------------*/
  945. void kwsysProcess_Kill(kwsysProcess* cp)
  946. {
  947. int i;
  948. /* Make sure we are executing a process. */
  949. if(!cp || cp->State != kwsysProcess_State_Executing)
  950. {
  951. return;
  952. }
  953. /* Kill the children. */
  954. cp->Killed = 1;
  955. for(i=0; i < cp->NumberOfCommands; ++i)
  956. {
  957. if(cp->ForkPIDs[i])
  958. {
  959. kwsysProcessKill(cp->ForkPIDs[i]);
  960. }
  961. }
  962. /* Close all the pipe read ends. */
  963. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  964. {
  965. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  966. }
  967. cp->PipesLeft = 0;
  968. }
  969. /*--------------------------------------------------------------------------*/
  970. /* Initialize a process control structure for kwsysProcess_Execute. */
  971. static int kwsysProcessInitialize(kwsysProcess* cp)
  972. {
  973. int i;
  974. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  975. {
  976. cp->PipeReadEnds[i] = -1;
  977. }
  978. cp->SelectError = 0;
  979. cp->StartTime.tv_sec = -1;
  980. cp->StartTime.tv_usec = -1;
  981. cp->TimeoutTime.tv_sec = -1;
  982. cp->TimeoutTime.tv_usec = -1;
  983. cp->TimeoutExpired = 0;
  984. cp->PipesLeft = 0;
  985. FD_ZERO(&cp->PipeSet);
  986. cp->State = kwsysProcess_State_Starting;
  987. cp->Killed = 0;
  988. cp->ExitException = kwsysProcess_Exception_None;
  989. cp->ExitCode = 1;
  990. cp->ExitValue = 1;
  991. cp->ErrorMessage[0] = 0;
  992. strcpy(cp->ExitExceptionString, "No exception");
  993. if(cp->ForkPIDs)
  994. {
  995. free(cp->ForkPIDs);
  996. }
  997. cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*cp->NumberOfCommands);
  998. if(!cp->ForkPIDs)
  999. {
  1000. return 0;
  1001. }
  1002. memset(cp->ForkPIDs, 0, sizeof(pid_t)*cp->NumberOfCommands);
  1003. if(cp->CommandExitCodes)
  1004. {
  1005. free(cp->CommandExitCodes);
  1006. }
  1007. cp->CommandExitCodes = (int*)malloc(sizeof(int)*cp->NumberOfCommands);
  1008. if(!cp->CommandExitCodes)
  1009. {
  1010. return 0;
  1011. }
  1012. memset(cp->CommandExitCodes, 0, sizeof(int)*cp->NumberOfCommands);
  1013. /* Allocate memory to save the real working directory. */
  1014. if ( cp->WorkingDirectory )
  1015. {
  1016. #if defined(MAXPATHLEN)
  1017. cp->RealWorkingDirectoryLength = MAXPATHLEN;
  1018. #elif defined(PATH_MAX)
  1019. cp->RealWorkingDirectoryLength = PATH_MAX;
  1020. #else
  1021. cp->RealWorkingDirectoryLength = 4096;
  1022. #endif
  1023. cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength);
  1024. if(!cp->RealWorkingDirectory)
  1025. {
  1026. return 0;
  1027. }
  1028. }
  1029. return 1;
  1030. }
  1031. /*--------------------------------------------------------------------------*/
  1032. /* Free all resources used by the given kwsysProcess instance that were
  1033. allocated by kwsysProcess_Execute. */
  1034. static void kwsysProcessCleanup(kwsysProcess* cp, int error)
  1035. {
  1036. int i;
  1037. if(error)
  1038. {
  1039. /* We are cleaning up due to an error. Report the error message
  1040. if one has not been provided already. */
  1041. if(cp->ErrorMessage[0] == 0)
  1042. {
  1043. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1044. }
  1045. /* Set the error state. */
  1046. cp->State = kwsysProcess_State_Error;
  1047. /* Kill any children already started. */
  1048. if(cp->ForkPIDs)
  1049. {
  1050. int status;
  1051. for(i=0; i < cp->NumberOfCommands; ++i)
  1052. {
  1053. if(cp->ForkPIDs[i])
  1054. {
  1055. /* Kill the child. */
  1056. kwsysProcessKill(cp->ForkPIDs[i]);
  1057. /* Reap the child. Keep trying until the call is not
  1058. interrupted. */
  1059. while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
  1060. (errno == EINTR));
  1061. }
  1062. }
  1063. }
  1064. /* Restore the working directory. */
  1065. if(cp->RealWorkingDirectory)
  1066. {
  1067. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  1068. }
  1069. }
  1070. /* Restore the SIGCHLD handler. */
  1071. while((sigaction(SIGCHLD, &cp->OldSigChldAction, 0) < 0) &&
  1072. (errno == EINTR));
  1073. /* Free memory. */
  1074. if(cp->ForkPIDs)
  1075. {
  1076. free(cp->ForkPIDs);
  1077. cp->ForkPIDs = 0;
  1078. }
  1079. if(cp->RealWorkingDirectory)
  1080. {
  1081. free(cp->RealWorkingDirectory);
  1082. cp->RealWorkingDirectory = 0;
  1083. }
  1084. /* Close pipe handles. */
  1085. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  1086. {
  1087. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  1088. }
  1089. }
  1090. /*--------------------------------------------------------------------------*/
  1091. /* Close the given file descriptor if it is open. Reset its value to -1. */
  1092. static void kwsysProcessCleanupDescriptor(int* pfd)
  1093. {
  1094. if(pfd && *pfd >= 0)
  1095. {
  1096. /* Keep trying to close until it is not interrupted by a
  1097. * signal. */
  1098. while((close(*pfd) < 0) && (errno == EINTR));
  1099. *pfd = -1;
  1100. }
  1101. }
  1102. /*--------------------------------------------------------------------------*/
  1103. static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
  1104. kwsysProcessCreateInformation* si, int* readEnd)
  1105. {
  1106. /* Setup the process's stdin. */
  1107. if(prIndex > 0)
  1108. {
  1109. si->StdIn = *readEnd;
  1110. *readEnd = 0;
  1111. }
  1112. else if(cp->PipeFileSTDIN)
  1113. {
  1114. /* Open a file for the child's stdin to read. */
  1115. si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
  1116. if(si->StdIn < 0)
  1117. {
  1118. return 0;
  1119. }
  1120. /* Set close-on-exec flag on the pipe's end. */
  1121. if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
  1122. {
  1123. return 0;
  1124. }
  1125. }
  1126. else if(cp->PipeSharedSTDIN)
  1127. {
  1128. si->StdIn = 0;
  1129. }
  1130. else
  1131. {
  1132. si->StdIn = -1;
  1133. }
  1134. /* Setup the process's stdout. */
  1135. {
  1136. /* Create the pipe. */
  1137. int p[2];
  1138. if(pipe(p) < 0)
  1139. {
  1140. return 0;
  1141. }
  1142. *readEnd = p[0];
  1143. si->StdOut = p[1];
  1144. /* Set close-on-exec flag on the pipe's ends. */
  1145. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  1146. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  1147. {
  1148. return 0;
  1149. }
  1150. }
  1151. /* Replace the stdout pipe with a file if requested. In this case
  1152. the select call will report that stdout is closed immediately. */
  1153. if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
  1154. {
  1155. if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
  1156. {
  1157. return 0;
  1158. }
  1159. }
  1160. /* Replace the stdout pipe with the parent's if requested. In this
  1161. case the select call will report that stderr is closed
  1162. immediately. */
  1163. if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
  1164. {
  1165. kwsysProcessCleanupDescriptor(&si->StdOut);
  1166. si->StdOut = 1;
  1167. }
  1168. /* Create the error reporting pipe. */
  1169. if(pipe(si->ErrorPipe) < 0)
  1170. {
  1171. return 0;
  1172. }
  1173. /* Set close-on-exec flag on the error pipe's write end. */
  1174. if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
  1175. {
  1176. return 0;
  1177. }
  1178. /* Fork off a child process. */
  1179. cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
  1180. if(cp->ForkPIDs[prIndex] < 0)
  1181. {
  1182. return 0;
  1183. }
  1184. if(cp->ForkPIDs[prIndex] == 0)
  1185. {
  1186. /* Close the read end of the error reporting pipe. */
  1187. close(si->ErrorPipe[0]);
  1188. /* Setup the stdin, stdout, and stderr pipes. */
  1189. if(si->StdIn > 0)
  1190. {
  1191. dup2(si->StdIn, 0);
  1192. }
  1193. else if(si->StdIn < 0)
  1194. {
  1195. close(0);
  1196. }
  1197. if(si->StdOut != 1)
  1198. {
  1199. dup2(si->StdOut, 1);
  1200. }
  1201. if(si->StdErr != 2)
  1202. {
  1203. dup2(si->StdErr, 2);
  1204. }
  1205. /* Clear the close-on-exec flag for stdin, stdout, and stderr.
  1206. Also clear it for the termination pipe. All other pipe handles
  1207. will be closed when exec succeeds. */
  1208. fcntl(0, F_SETFD, 0);
  1209. fcntl(1, F_SETFD, 0);
  1210. fcntl(2, F_SETFD, 0);
  1211. fcntl(si->TermPipe, F_SETFD, 0);
  1212. /* Restore all default signal handlers. */
  1213. kwsysProcessRestoreDefaultSignalHandlers();
  1214. /* Execute the real process. If successful, this does not return. */
  1215. execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
  1216. /* Failure. Report error to parent and terminate. */
  1217. kwsysProcessChildErrorExit(si->ErrorPipe[1]);
  1218. }
  1219. /* We are done with the error reporting pipe write end. */
  1220. kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
  1221. /* Block until the child's exec call succeeds and closes the error
  1222. pipe or writes data to the pipe to report an error. */
  1223. {
  1224. int total = 0;
  1225. int n = 1;
  1226. /* Read the entire error message up to the length of our buffer. */
  1227. while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
  1228. {
  1229. /* Keep trying to read until the operation is not interrupted. */
  1230. while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
  1231. KWSYSPE_PIPE_BUFFER_SIZE-total)) < 0) &&
  1232. (errno == EINTR));
  1233. if(n > 0)
  1234. {
  1235. total += n;
  1236. }
  1237. }
  1238. /* We are done with the error reporting pipe read end. */
  1239. kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
  1240. if(total > 0)
  1241. {
  1242. /* The child failed to execute the process. */
  1243. return 0;
  1244. }
  1245. }
  1246. /* Successfully created this child process. */
  1247. if(prIndex > 0 || si->StdIn > 0)
  1248. {
  1249. /* The parent process does not need the input pipe read end. */
  1250. kwsysProcessCleanupDescriptor(&si->StdIn);
  1251. }
  1252. /* The parent process does not need the output pipe write ends. */
  1253. if(si->StdOut != 1)
  1254. {
  1255. kwsysProcessCleanupDescriptor(&si->StdOut);
  1256. }
  1257. return 1;
  1258. }
  1259. /*--------------------------------------------------------------------------*/
  1260. static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
  1261. {
  1262. int fout;
  1263. if(!name)
  1264. {
  1265. return 1;
  1266. }
  1267. /* Close the existing descriptor. */
  1268. kwsysProcessCleanupDescriptor(p);
  1269. /* Open a file for the pipe to write (permissions 644). */
  1270. if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC,
  1271. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
  1272. {
  1273. return 0;
  1274. }
  1275. /* Set close-on-exec flag on the pipe's end. */
  1276. if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
  1277. {
  1278. return 0;
  1279. }
  1280. /* Assign the replacement descriptor. */
  1281. *p = fout;
  1282. return 1;
  1283. }
  1284. /*--------------------------------------------------------------------------*/
  1285. /* Get the time at which either the process or user timeout will
  1286. expire. Returns 1 if the user timeout is first, and 0 otherwise. */
  1287. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  1288. kwsysProcessTime* timeoutTime)
  1289. {
  1290. /* The first time this is called, we need to calculate the time at
  1291. which the child will timeout. */
  1292. if(cp->Timeout && cp->TimeoutTime.tv_sec < 0)
  1293. {
  1294. kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
  1295. cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
  1296. }
  1297. /* Start with process timeout. */
  1298. *timeoutTime = cp->TimeoutTime;
  1299. /* Check if the user timeout is earlier. */
  1300. if(userTimeout)
  1301. {
  1302. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1303. kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
  1304. kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
  1305. userTimeoutLength);
  1306. if(timeoutTime->tv_sec < 0 ||
  1307. kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
  1308. {
  1309. *timeoutTime = userTimeoutTime;
  1310. return 1;
  1311. }
  1312. }
  1313. return 0;
  1314. }
  1315. /*--------------------------------------------------------------------------*/
  1316. /* Get the length of time before the given timeout time arrives.
  1317. Returns 1 if the time has already arrived, and 0 otherwise. */
  1318. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  1319. double* userTimeout,
  1320. kwsysProcessTimeNative* timeoutLength)
  1321. {
  1322. if(timeoutTime->tv_sec < 0)
  1323. {
  1324. /* No timeout time has been requested. */
  1325. return 0;
  1326. }
  1327. else
  1328. {
  1329. /* Calculate the remaining time. */
  1330. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1331. kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
  1332. currentTime);
  1333. if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
  1334. {
  1335. /* Caller has explicitly requested a zero timeout. */
  1336. timeLeft.tv_sec = 0;
  1337. timeLeft.tv_usec = 0;
  1338. }
  1339. if(timeLeft.tv_sec < 0)
  1340. {
  1341. /* Timeout has already expired. */
  1342. return 1;
  1343. }
  1344. else
  1345. {
  1346. /* There is some time left. */
  1347. timeoutLength->tv_sec = timeLeft.tv_sec;
  1348. timeoutLength->tv_usec = timeLeft.tv_usec;
  1349. return 0;
  1350. }
  1351. }
  1352. }
  1353. /*--------------------------------------------------------------------------*/
  1354. static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
  1355. {
  1356. kwsysProcessTime current;
  1357. kwsysProcessTimeNative current_native;
  1358. gettimeofday(&current_native, 0);
  1359. current.tv_sec = (long)current_native.tv_sec;
  1360. current.tv_usec = (long)current_native.tv_usec;
  1361. return current;
  1362. }
  1363. /*--------------------------------------------------------------------------*/
  1364. static double kwsysProcessTimeToDouble(kwsysProcessTime t)
  1365. {
  1366. return (double)t.tv_sec + t.tv_usec*0.000001;
  1367. }
  1368. /*--------------------------------------------------------------------------*/
  1369. static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
  1370. {
  1371. kwsysProcessTime t;
  1372. t.tv_sec = (long)d;
  1373. t.tv_usec = (long)((d-t.tv_sec)*1000000);
  1374. return t;
  1375. }
  1376. /*--------------------------------------------------------------------------*/
  1377. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
  1378. {
  1379. return ((in1.tv_sec < in2.tv_sec) ||
  1380. ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
  1381. }
  1382. /*--------------------------------------------------------------------------*/
  1383. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
  1384. {
  1385. kwsysProcessTime out;
  1386. out.tv_sec = in1.tv_sec + in2.tv_sec;
  1387. out.tv_usec = in1.tv_usec + in2.tv_usec;
  1388. if(out.tv_usec > 1000000)
  1389. {
  1390. out.tv_usec -= 1000000;
  1391. out.tv_sec += 1;
  1392. }
  1393. return out;
  1394. }
  1395. /*--------------------------------------------------------------------------*/
  1396. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
  1397. {
  1398. kwsysProcessTime out;
  1399. out.tv_sec = in1.tv_sec - in2.tv_sec;
  1400. out.tv_usec = in1.tv_usec - in2.tv_usec;
  1401. if(out.tv_usec < 0)
  1402. {
  1403. out.tv_usec += 1000000;
  1404. out.tv_sec -= 1;
  1405. }
  1406. return out;
  1407. }
  1408. /*--------------------------------------------------------------------------*/
  1409. #define KWSYSPE_CASE(type, str) \
  1410. cp->ExitException = kwsysProcess_Exception_##type; \
  1411. strcpy(cp->ExitExceptionString, str)
  1412. static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
  1413. {
  1414. switch (sig)
  1415. {
  1416. #ifdef SIGSEGV
  1417. case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
  1418. #endif
  1419. #ifdef SIGBUS
  1420. # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
  1421. case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
  1422. # endif
  1423. #endif
  1424. #ifdef SIGFPE
  1425. case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
  1426. #endif
  1427. #ifdef SIGILL
  1428. case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
  1429. #endif
  1430. #ifdef SIGINT
  1431. case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
  1432. #endif
  1433. #ifdef SIGABRT
  1434. case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
  1435. #endif
  1436. #ifdef SIGKILL
  1437. case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
  1438. #endif
  1439. #ifdef SIGTERM
  1440. case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
  1441. #endif
  1442. #ifdef SIGHUP
  1443. case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
  1444. #endif
  1445. #ifdef SIGQUIT
  1446. case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
  1447. #endif
  1448. #ifdef SIGTRAP
  1449. case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
  1450. #endif
  1451. #ifdef SIGIOT
  1452. # if !defined(SIGABRT) || SIGIOT != SIGABRT
  1453. case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
  1454. # endif
  1455. #endif
  1456. #ifdef SIGUSR1
  1457. case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
  1458. #endif
  1459. #ifdef SIGUSR2
  1460. case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
  1461. #endif
  1462. #ifdef SIGPIPE
  1463. case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
  1464. #endif
  1465. #ifdef SIGALRM
  1466. case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
  1467. #endif
  1468. #ifdef SIGSTKFLT
  1469. case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
  1470. #endif
  1471. #ifdef SIGCHLD
  1472. case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
  1473. #elif defined(SIGCLD)
  1474. case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
  1475. #endif
  1476. #ifdef SIGCONT
  1477. case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
  1478. #endif
  1479. #ifdef SIGSTOP
  1480. case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
  1481. #endif
  1482. #ifdef SIGTSTP
  1483. case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
  1484. #endif
  1485. #ifdef SIGTTIN
  1486. case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
  1487. #endif
  1488. #ifdef SIGTTOU
  1489. case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
  1490. #endif
  1491. #ifdef SIGURG
  1492. case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
  1493. #endif
  1494. #ifdef SIGXCPU
  1495. case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
  1496. #endif
  1497. #ifdef SIGXFSZ
  1498. case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
  1499. #endif
  1500. #ifdef SIGVTALRM
  1501. case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
  1502. #endif
  1503. #ifdef SIGPROF
  1504. case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
  1505. #endif
  1506. #ifdef SIGWINCH
  1507. case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
  1508. #endif
  1509. #ifdef SIGPOLL
  1510. case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
  1511. #endif
  1512. #ifdef SIGIO
  1513. # if !defined(SIGPOLL) || SIGIO != SIGPOLL
  1514. case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
  1515. # endif
  1516. #endif
  1517. #ifdef SIGPWR
  1518. case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
  1519. #endif
  1520. #ifdef SIGSYS
  1521. case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
  1522. #endif
  1523. #ifdef SIGUNUSED
  1524. # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
  1525. case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
  1526. # endif
  1527. #endif
  1528. default:
  1529. cp->ExitException = kwsysProcess_Exception_Other;
  1530. sprintf(cp->ExitExceptionString, "Signal %d", sig);
  1531. break;
  1532. }
  1533. }
  1534. #undef KWSYSPE_CASE
  1535. /*--------------------------------------------------------------------------*/
  1536. /* When the child process encounters an error before its program is
  1537. invoked, this is called to report the error to the parent and
  1538. exit. */
  1539. static void kwsysProcessChildErrorExit(int errorPipe)
  1540. {
  1541. /* Construct the error message. */
  1542. char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
  1543. strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1544. /* Report the error to the parent through the special pipe. */
  1545. write(errorPipe, buffer, strlen(buffer));
  1546. /* Terminate without cleanup. */
  1547. _exit(1);
  1548. }
  1549. /*--------------------------------------------------------------------------*/
  1550. /* Restores all signal handlers to their default values. */
  1551. static void kwsysProcessRestoreDefaultSignalHandlers(void)
  1552. {
  1553. struct sigaction act;
  1554. memset(&act, 0, sizeof(struct sigaction));
  1555. act.sa_handler = SIG_DFL;
  1556. #ifdef SIGHUP
  1557. sigaction(SIGHUP, &act, 0);
  1558. #endif
  1559. #ifdef SIGINT
  1560. sigaction(SIGINT, &act, 0);
  1561. #endif
  1562. #ifdef SIGQUIT
  1563. sigaction(SIGQUIT, &act, 0);
  1564. #endif
  1565. #ifdef SIGILL
  1566. sigaction(SIGILL, &act, 0);
  1567. #endif
  1568. #ifdef SIGTRAP
  1569. sigaction(SIGTRAP, &act, 0);
  1570. #endif
  1571. #ifdef SIGABRT
  1572. sigaction(SIGABRT, &act, 0);
  1573. #endif
  1574. #ifdef SIGIOT
  1575. sigaction(SIGIOT, &act, 0);
  1576. #endif
  1577. #ifdef SIGBUS
  1578. sigaction(SIGBUS, &act, 0);
  1579. #endif
  1580. #ifdef SIGFPE
  1581. sigaction(SIGFPE, &act, 0);
  1582. #endif
  1583. #ifdef SIGUSR1
  1584. sigaction(SIGUSR1, &act, 0);
  1585. #endif
  1586. #ifdef SIGSEGV
  1587. sigaction(SIGSEGV, &act, 0);
  1588. #endif
  1589. #ifdef SIGUSR2
  1590. sigaction(SIGUSR2, &act, 0);
  1591. #endif
  1592. #ifdef SIGPIPE
  1593. sigaction(SIGPIPE, &act, 0);
  1594. #endif
  1595. #ifdef SIGALRM
  1596. sigaction(SIGALRM, &act, 0);
  1597. #endif
  1598. #ifdef SIGTERM
  1599. sigaction(SIGTERM, &act, 0);
  1600. #endif
  1601. #ifdef SIGSTKFLT
  1602. sigaction(SIGSTKFLT, &act, 0);
  1603. #endif
  1604. #ifdef SIGCLD
  1605. sigaction(SIGCLD, &act, 0);
  1606. #endif
  1607. #ifdef SIGCHLD
  1608. sigaction(SIGCHLD, &act, 0);
  1609. #endif
  1610. #ifdef SIGCONT
  1611. sigaction(SIGCONT, &act, 0);
  1612. #endif
  1613. #ifdef SIGTSTP
  1614. sigaction(SIGTSTP, &act, 0);
  1615. #endif
  1616. #ifdef SIGTTIN
  1617. sigaction(SIGTTIN, &act, 0);
  1618. #endif
  1619. #ifdef SIGTTOU
  1620. sigaction(SIGTTOU, &act, 0);
  1621. #endif
  1622. #ifdef SIGURG
  1623. sigaction(SIGURG, &act, 0);
  1624. #endif
  1625. #ifdef SIGXCPU
  1626. sigaction(SIGXCPU, &act, 0);
  1627. #endif
  1628. #ifdef SIGXFSZ
  1629. sigaction(SIGXFSZ, &act, 0);
  1630. #endif
  1631. #ifdef SIGVTALRM
  1632. sigaction(SIGVTALRM, &act, 0);
  1633. #endif
  1634. #ifdef SIGPROF
  1635. sigaction(SIGPROF, &act, 0);
  1636. #endif
  1637. #ifdef SIGWINCH
  1638. sigaction(SIGWINCH, &act, 0);
  1639. #endif
  1640. #ifdef SIGPOLL
  1641. sigaction(SIGPOLL, &act, 0);
  1642. #endif
  1643. #ifdef SIGIO
  1644. sigaction(SIGIO, &act, 0);
  1645. #endif
  1646. #ifdef SIGPWR
  1647. sigaction(SIGPWR, &act, 0);
  1648. #endif
  1649. #ifdef SIGSYS
  1650. sigaction(SIGSYS, &act, 0);
  1651. #endif
  1652. #ifdef SIGUNUSED
  1653. sigaction(SIGUNUSED, &act, 0);
  1654. #endif
  1655. }
  1656. /*--------------------------------------------------------------------------*/
  1657. static pid_t kwsysProcessFork(kwsysProcess* cp,
  1658. kwsysProcessCreateInformation* si)
  1659. {
  1660. /* Create a detached process if requested. */
  1661. if(cp->OptionDetach)
  1662. {
  1663. /* Create an intermediate process. */
  1664. pid_t middle_pid = fork();
  1665. if(middle_pid < 0)
  1666. {
  1667. /* Fork failed. Return as if we were not detaching. */
  1668. return middle_pid;
  1669. }
  1670. else if(middle_pid == 0)
  1671. {
  1672. /* This is the intermediate process. Create the real child. */
  1673. pid_t child_pid = fork();
  1674. if(child_pid == 0)
  1675. {
  1676. /* This is the real child process. There is nothing to do here. */
  1677. return 0;
  1678. }
  1679. else
  1680. {
  1681. /* Use the error pipe to report the pid to the real parent. */
  1682. while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
  1683. (errno == EINTR));
  1684. /* Exit without cleanup. The parent holds all resources. */
  1685. _exit(0);
  1686. return 0; /* Never reached, but avoids SunCC warning. */
  1687. }
  1688. }
  1689. else
  1690. {
  1691. /* This is the original parent process. The intermediate
  1692. process will use the error pipe to report the pid of the
  1693. detached child. */
  1694. pid_t child_pid;
  1695. int status;
  1696. while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
  1697. (errno == EINTR));
  1698. /* Wait for the intermediate process to exit and clean it up. */
  1699. while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
  1700. return child_pid;
  1701. }
  1702. }
  1703. else
  1704. {
  1705. /* Not creating a detached process. Use normal fork. */
  1706. return fork();
  1707. }
  1708. }
  1709. /*--------------------------------------------------------------------------*/
  1710. /* We try to obtain process information by invoking the ps command.
  1711. Here we define the command to call on each platform and the
  1712. corresponding parsing format string. The parsing format should
  1713. have two integers to store: the pid and then the ppid. */
  1714. #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
  1715. # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
  1716. # define KWSYSPE_PS_FORMAT "%d %d\n"
  1717. #elif defined(__hpux) || defined(__sparc) || defined(__sgi) || defined(_AIX)
  1718. # define KWSYSPE_PS_COMMAND "ps -ef"
  1719. # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
  1720. #elif defined(__CYGWIN__)
  1721. # define KWSYSPE_PS_COMMAND "ps aux"
  1722. # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
  1723. #endif
  1724. /*--------------------------------------------------------------------------*/
  1725. static void kwsysProcessKill(pid_t process_id)
  1726. {
  1727. #if defined(__linux__) || defined(__CYGWIN__)
  1728. DIR* procdir;
  1729. #endif
  1730. /* Suspend the process to be sure it will not create more children. */
  1731. kill(process_id, SIGSTOP);
  1732. /* Kill all children if we can find them. */
  1733. #if defined(__linux__) || defined(__CYGWIN__)
  1734. /* First try using the /proc filesystem. */
  1735. if((procdir = opendir("/proc")) != NULL)
  1736. {
  1737. #if defined(MAXPATHLEN)
  1738. char fname[MAXPATHLEN];
  1739. #elif defined(PATH_MAX)
  1740. char fname[PATH_MAX];
  1741. #else
  1742. char fname[4096];
  1743. #endif
  1744. char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
  1745. struct dirent* d;
  1746. /* Each process has a directory in /proc whose name is the pid.
  1747. Within this directory is a file called stat that has the
  1748. following format:
  1749. pid (command line) status ppid ...
  1750. We want to get the ppid for all processes. Those that have
  1751. process_id as their parent should be recursively killed. */
  1752. for(d = readdir(procdir); d; d = readdir(procdir))
  1753. {
  1754. int pid;
  1755. if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
  1756. {
  1757. struct stat finfo;
  1758. sprintf(fname, "/proc/%d/stat", pid);
  1759. if(stat(fname, &finfo) == 0)
  1760. {
  1761. FILE* f = fopen(fname, "r");
  1762. if(f)
  1763. {
  1764. int nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
  1765. buffer[nread] = '\0';
  1766. if(nread > 0)
  1767. {
  1768. const char* rparen = strrchr(buffer, ')');
  1769. int ppid;
  1770. if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
  1771. {
  1772. if(ppid == process_id)
  1773. {
  1774. /* Recursively kill this child and its children. */
  1775. kwsysProcessKill(pid);
  1776. }
  1777. }
  1778. }
  1779. fclose(f);
  1780. }
  1781. }
  1782. }
  1783. }
  1784. closedir(procdir);
  1785. }
  1786. else
  1787. #endif
  1788. {
  1789. #if defined(KWSYSPE_PS_COMMAND)
  1790. /* Try running "ps" to get the process information. */
  1791. FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
  1792. /* Make sure the process started and provided a valid header. */
  1793. if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
  1794. {
  1795. /* Look for processes whose parent is the process being killed. */
  1796. int pid, ppid;
  1797. while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
  1798. {
  1799. if(ppid == process_id)
  1800. {
  1801. /* Recursively kill this child aned its children. */
  1802. kwsysProcessKill(pid);
  1803. }
  1804. }
  1805. }
  1806. /* We are done with the ps process. */
  1807. if(ps)
  1808. {
  1809. pclose(ps);
  1810. }
  1811. #endif
  1812. }
  1813. /* Kill the process. */
  1814. kill(process_id, SIGKILL);
  1815. }