ProcessUNIX.c 51 KB

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