ProcessUNIX.c 51 KB

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