ProcessUNIX.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  1. /*=========================================================================
  2. Program: KWSys - Kitware System Library
  3. Module: $RCSfile$
  4. Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.
  5. See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even
  7. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  8. PURPOSE. See the above copyright notices for more information.
  9. =========================================================================*/
  10. #include "kwsysPrivate.h"
  11. #include KWSYS_HEADER(Process.h)
  12. /* Work-around CMake dependency scanning limitation. This must
  13. duplicate the above list of headers. */
  14. #if 0
  15. # include "Process.h.in"
  16. #endif
  17. /*
  18. Implementation for UNIX
  19. On UNIX, a child process is forked to exec the program. Three output
  20. pipes are read by the parent process using a select call to block
  21. until data are ready. Two of the pipes are stdout and stderr for the
  22. child. The third is a special pipe populated by a signal handler to
  23. indicate that a child has terminated. This is used in conjunction
  24. with the timeout on the select call to implement a timeout for program
  25. even when it closes stdout and stderr and at the same time avoiding
  26. races.
  27. */
  28. /*
  29. TODO:
  30. We cannot create the pipeline of processes in suspended states. How
  31. do we cleanup processes already started when one fails to load? Right
  32. now we are just killing them, which is probably not the right thing to
  33. do.
  34. */
  35. #include <stdio.h> /* snprintf */
  36. #include <stdlib.h> /* malloc, free */
  37. #include <string.h> /* strdup, strerror, memset */
  38. #include <sys/time.h> /* struct timeval */
  39. #include <sys/types.h> /* pid_t, fd_set */
  40. #include <sys/wait.h> /* waitpid */
  41. #include <sys/stat.h> /* open mode */
  42. #include <unistd.h> /* pipe, close, fork, execvp, select, _exit */
  43. #include <fcntl.h> /* fcntl */
  44. #include <errno.h> /* errno */
  45. #include <time.h> /* gettimeofday */
  46. #include <signal.h> /* sigaction */
  47. #include <dirent.h> /* DIR, dirent */
  48. #include <ctype.h> /* isspace */
  49. /* The number of pipes for the child's output. The standard stdout
  50. and stderr pipes are the first two. One more pipe is used to
  51. detect when the child process has terminated. The third pipe is
  52. not given to the child process, so it cannot close it until it
  53. terminates. */
  54. #define KWSYSPE_PIPE_COUNT 3
  55. #define KWSYSPE_PIPE_STDOUT 0
  56. #define KWSYSPE_PIPE_STDERR 1
  57. #define KWSYSPE_PIPE_SIGNAL 2
  58. /* The maximum amount to read from a pipe at a time. */
  59. #define KWSYSPE_PIPE_BUFFER_SIZE 1024
  60. /* Keep track of times using a signed representation. Switch to the
  61. native (possibly unsigned) representation only when calling native
  62. functions. */
  63. typedef struct timeval kwsysProcessTimeNative;
  64. typedef struct kwsysProcessTime_s kwsysProcessTime;
  65. struct kwsysProcessTime_s
  66. {
  67. long tv_sec;
  68. long tv_usec;
  69. };
  70. typedef struct kwsysProcessCreateInformation_s
  71. {
  72. int StdIn;
  73. int StdOut;
  74. int StdErr;
  75. int ErrorPipe[2];
  76. } kwsysProcessCreateInformation;
  77. /*--------------------------------------------------------------------------*/
  78. static int kwsysProcessInitialize(kwsysProcess* cp);
  79. static void kwsysProcessCleanup(kwsysProcess* cp, int error);
  80. static void kwsysProcessCleanupDescriptor(int* pfd);
  81. static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
  82. kwsysProcessCreateInformation* si, int* readEnd);
  83. static void kwsysProcessDestroy(kwsysProcess* cp);
  84. static int kwsysProcessSetupOutputPipeFile(int* p, const char* name);
  85. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  86. kwsysProcessTime* timeoutTime);
  87. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  88. double* userTimeout,
  89. kwsysProcessTimeNative* timeoutLength);
  90. static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
  91. static double kwsysProcessTimeToDouble(kwsysProcessTime t);
  92. static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
  93. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
  94. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
  95. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
  96. static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
  97. static void kwsysProcessChildErrorExit(int errorPipe);
  98. static void kwsysProcessRestoreDefaultSignalHandlers(void);
  99. static pid_t kwsysProcessFork(kwsysProcess* cp,
  100. kwsysProcessCreateInformation* si);
  101. static void kwsysProcessKill(pid_t process_id);
  102. static int kwsysProcessesAdd(kwsysProcess* cp);
  103. static void kwsysProcessesRemove(kwsysProcess* cp);
  104. static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
  105. void* ucontext);
  106. static char** kwsysProcessParseVerbatimCommand(const char* command);
  107. /*--------------------------------------------------------------------------*/
  108. /* Structure containing data used to implement the child's execution. */
  109. struct kwsysProcess_s
  110. {
  111. /* The command lines to execute. */
  112. char*** Commands;
  113. int NumberOfCommands;
  114. /* Descriptors for the read ends of the child's output pipes and
  115. the signal pipe. */
  116. int PipeReadEnds[KWSYSPE_PIPE_COUNT];
  117. /* Write descriptor for child termination signal pipe. */
  118. int SignalPipe;
  119. /* Buffer for pipe data. */
  120. char PipeBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
  121. /* Process IDs returned by the calls to fork. */
  122. pid_t* ForkPIDs;
  123. /* Flag for whether the children were terminated by a faild select. */
  124. int SelectError;
  125. /* The timeout length. */
  126. double Timeout;
  127. /* The working directory for the process. */
  128. char* WorkingDirectory;
  129. /* Whether to create the child as a detached process. */
  130. int OptionDetach;
  131. /* Whether the child was created as a detached process. */
  132. int Detached;
  133. /* Whether to treat command lines as verbatim. */
  134. int Verbatim;
  135. /* Time at which the child started. Negative for no timeout. */
  136. kwsysProcessTime StartTime;
  137. /* Time at which the child will timeout. Negative for no timeout. */
  138. kwsysProcessTime TimeoutTime;
  139. /* Flag for whether the timeout expired. */
  140. int TimeoutExpired;
  141. /* The number of pipes left open during execution. */
  142. int PipesLeft;
  143. /* File descriptor set for call to select. */
  144. fd_set PipeSet;
  145. /* The number of children still executing. */
  146. int CommandsLeft;
  147. /* The current status of the child process. */
  148. int State;
  149. /* The exceptional behavior that terminated the child process, if
  150. * any. */
  151. int ExitException;
  152. /* The exit code of the child process. */
  153. int ExitCode;
  154. /* The exit value of the child process, if any. */
  155. int ExitValue;
  156. /* Whether the process was killed. */
  157. int Killed;
  158. /* Buffer for error message in case of failure. */
  159. char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
  160. /* Description for the ExitException. */
  161. char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
  162. /* The exit codes of each child process in the pipeline. */
  163. int* CommandExitCodes;
  164. /* Name of files to which stdin and stdout pipes are attached. */
  165. char* PipeFileSTDIN;
  166. char* PipeFileSTDOUT;
  167. char* PipeFileSTDERR;
  168. /* Whether each pipe is shared with the parent process. */
  169. int PipeSharedSTDIN;
  170. int PipeSharedSTDOUT;
  171. int PipeSharedSTDERR;
  172. /* The real working directory of this process. */
  173. int RealWorkingDirectoryLength;
  174. char* RealWorkingDirectory;
  175. };
  176. /*--------------------------------------------------------------------------*/
  177. kwsysProcess* kwsysProcess_New(void)
  178. {
  179. /* Allocate a process control structure. */
  180. kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
  181. if(!cp)
  182. {
  183. return 0;
  184. }
  185. memset(cp, 0, sizeof(kwsysProcess));
  186. /* Share stdin with the parent process by default. */
  187. cp->PipeSharedSTDIN = 1;
  188. /* Set initial status. */
  189. cp->State = kwsysProcess_State_Starting;
  190. return cp;
  191. }
  192. /*--------------------------------------------------------------------------*/
  193. void kwsysProcess_Delete(kwsysProcess* cp)
  194. {
  195. /* Make sure we have an instance. */
  196. if(!cp)
  197. {
  198. return;
  199. }
  200. /* If the process is executing, wait for it to finish. */
  201. if(cp->State == kwsysProcess_State_Executing)
  202. {
  203. if(cp->Detached)
  204. {
  205. kwsysProcess_Disown(cp);
  206. }
  207. else
  208. {
  209. kwsysProcess_WaitForExit(cp, 0);
  210. }
  211. }
  212. /* Free memory. */
  213. kwsysProcess_SetCommand(cp, 0);
  214. kwsysProcess_SetWorkingDirectory(cp, 0);
  215. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
  216. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
  217. kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
  218. if(cp->CommandExitCodes)
  219. {
  220. free(cp->CommandExitCodes);
  221. }
  222. free(cp);
  223. }
  224. /*--------------------------------------------------------------------------*/
  225. int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
  226. {
  227. int i;
  228. if(!cp)
  229. {
  230. return 0;
  231. }
  232. for(i=0; i < cp->NumberOfCommands; ++i)
  233. {
  234. char** c = cp->Commands[i];
  235. while(*c)
  236. {
  237. free(*c++);
  238. }
  239. free(cp->Commands[i]);
  240. }
  241. cp->NumberOfCommands = 0;
  242. if(cp->Commands)
  243. {
  244. free(cp->Commands);
  245. cp->Commands = 0;
  246. }
  247. if(command)
  248. {
  249. return kwsysProcess_AddCommand(cp, command);
  250. }
  251. return 1;
  252. }
  253. /*--------------------------------------------------------------------------*/
  254. int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
  255. {
  256. int newNumberOfCommands;
  257. char*** newCommands;
  258. /* Make sure we have a command to add. */
  259. if(!cp || !command || !*command)
  260. {
  261. return 0;
  262. }
  263. /* Allocate a new array for command pointers. */
  264. newNumberOfCommands = cp->NumberOfCommands + 1;
  265. if(!(newCommands = (char***)malloc(sizeof(char**) * newNumberOfCommands)))
  266. {
  267. /* Out of memory. */
  268. return 0;
  269. }
  270. /* Copy any existing commands into the new array. */
  271. {
  272. int i;
  273. for(i=0; i < cp->NumberOfCommands; ++i)
  274. {
  275. newCommands[i] = cp->Commands[i];
  276. }
  277. }
  278. /* Add the new command. */
  279. if(cp->Verbatim)
  280. {
  281. /* In order to run the given command line verbatim we need to
  282. parse it. */
  283. newCommands[cp->NumberOfCommands] =
  284. kwsysProcessParseVerbatimCommand(*command);
  285. if(!newCommands[cp->NumberOfCommands])
  286. {
  287. /* Out of memory. */
  288. free(newCommands);
  289. return 0;
  290. }
  291. }
  292. else
  293. {
  294. /* Copy each argument string individually. */
  295. char const* const* c = command;
  296. int n = 0;
  297. int i = 0;
  298. while(*c++);
  299. n = c - command - 1;
  300. newCommands[cp->NumberOfCommands] = (char**)malloc((n+1)*sizeof(char*));
  301. if(!newCommands[cp->NumberOfCommands])
  302. {
  303. /* Out of memory. */
  304. free(newCommands);
  305. return 0;
  306. }
  307. for(i=0; i < n; ++i)
  308. {
  309. newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
  310. if(!newCommands[cp->NumberOfCommands][i])
  311. {
  312. break;
  313. }
  314. }
  315. if(i < n)
  316. {
  317. /* Out of memory. */
  318. for(;i > 0; --i)
  319. {
  320. free(newCommands[cp->NumberOfCommands][i-1]);
  321. }
  322. free(newCommands);
  323. return 0;
  324. }
  325. newCommands[cp->NumberOfCommands][n] = 0;
  326. }
  327. /* Successfully allocated new command array. Free the old array. */
  328. free(cp->Commands);
  329. cp->Commands = newCommands;
  330. cp->NumberOfCommands = newNumberOfCommands;
  331. return 1;
  332. }
  333. /*--------------------------------------------------------------------------*/
  334. void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
  335. {
  336. if(!cp)
  337. {
  338. return;
  339. }
  340. cp->Timeout = timeout;
  341. if(cp->Timeout < 0)
  342. {
  343. cp->Timeout = 0;
  344. }
  345. }
  346. /*--------------------------------------------------------------------------*/
  347. int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
  348. {
  349. if(!cp)
  350. {
  351. return 0;
  352. }
  353. if(cp->WorkingDirectory == dir)
  354. {
  355. return 1;
  356. }
  357. if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
  358. {
  359. return 1;
  360. }
  361. if(cp->WorkingDirectory)
  362. {
  363. free(cp->WorkingDirectory);
  364. cp->WorkingDirectory = 0;
  365. }
  366. if(dir)
  367. {
  368. cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
  369. if(!cp->WorkingDirectory)
  370. {
  371. return 0;
  372. }
  373. strcpy(cp->WorkingDirectory, dir);
  374. }
  375. return 1;
  376. }
  377. /*--------------------------------------------------------------------------*/
  378. int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
  379. {
  380. char** pfile;
  381. if(!cp)
  382. {
  383. return 0;
  384. }
  385. switch(prPipe)
  386. {
  387. case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
  388. case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
  389. case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
  390. default: return 0;
  391. }
  392. if(*pfile)
  393. {
  394. free(*pfile);
  395. *pfile = 0;
  396. }
  397. if(file)
  398. {
  399. *pfile = malloc(strlen(file)+1);
  400. if(!*pfile)
  401. {
  402. return 0;
  403. }
  404. strcpy(*pfile, file);
  405. }
  406. /* If we are redirecting the pipe, do not share it. */
  407. if(*pfile)
  408. {
  409. kwsysProcess_SetPipeShared(cp, prPipe, 0);
  410. }
  411. return 1;
  412. }
  413. /*--------------------------------------------------------------------------*/
  414. void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
  415. {
  416. if(!cp)
  417. {
  418. return;
  419. }
  420. switch(prPipe)
  421. {
  422. case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
  423. case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
  424. case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
  425. default: return;
  426. }
  427. /* If we are sharing the pipe, do not redirect it to a file. */
  428. if(shared)
  429. {
  430. kwsysProcess_SetPipeFile(cp, prPipe, 0);
  431. }
  432. }
  433. /*--------------------------------------------------------------------------*/
  434. int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
  435. {
  436. if(!cp)
  437. {
  438. return 0;
  439. }
  440. switch(optionId)
  441. {
  442. case kwsysProcess_Option_Detach: return cp->OptionDetach;
  443. case kwsysProcess_Option_Verbatim: return cp->Verbatim;
  444. default: return 0;
  445. }
  446. }
  447. /*--------------------------------------------------------------------------*/
  448. void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
  449. {
  450. if(!cp)
  451. {
  452. return;
  453. }
  454. switch(optionId)
  455. {
  456. case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
  457. case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
  458. default: break;
  459. }
  460. }
  461. /*--------------------------------------------------------------------------*/
  462. int kwsysProcess_GetState(kwsysProcess* cp)
  463. {
  464. return cp? cp->State : kwsysProcess_State_Error;
  465. }
  466. /*--------------------------------------------------------------------------*/
  467. int kwsysProcess_GetExitException(kwsysProcess* cp)
  468. {
  469. return cp? cp->ExitException : kwsysProcess_Exception_Other;
  470. }
  471. /*--------------------------------------------------------------------------*/
  472. int kwsysProcess_GetExitCode(kwsysProcess* cp)
  473. {
  474. return cp? cp->ExitCode : 0;
  475. }
  476. /*--------------------------------------------------------------------------*/
  477. int kwsysProcess_GetExitValue(kwsysProcess* cp)
  478. {
  479. return cp? cp->ExitValue : -1;
  480. }
  481. /*--------------------------------------------------------------------------*/
  482. const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
  483. {
  484. if(!cp)
  485. {
  486. return "Process management structure could not be allocated";
  487. }
  488. else if(cp->State == kwsysProcess_State_Error)
  489. {
  490. return cp->ErrorMessage;
  491. }
  492. return "Success";
  493. }
  494. /*--------------------------------------------------------------------------*/
  495. const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
  496. {
  497. if(!cp)
  498. {
  499. return "GetExceptionString called with NULL process management structure";
  500. }
  501. else if(cp->State == kwsysProcess_State_Exception)
  502. {
  503. return cp->ExitExceptionString;
  504. }
  505. return "No exception";
  506. }
  507. /*--------------------------------------------------------------------------*/
  508. void kwsysProcess_Execute(kwsysProcess* cp)
  509. {
  510. int i;
  511. kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
  512. /* Do not execute a second copy simultaneously. */
  513. if(!cp || cp->State == kwsysProcess_State_Executing)
  514. {
  515. return;
  516. }
  517. /* Initialize the control structure for a new process. */
  518. if(!kwsysProcessInitialize(cp))
  519. {
  520. strcpy(cp->ErrorMessage, "Out of memory");
  521. cp->State = kwsysProcess_State_Error;
  522. return;
  523. }
  524. /* Save the real working directory of this process and change to
  525. the working directory for the child processes. This is needed
  526. to make pipe file paths evaluate correctly. */
  527. if(cp->WorkingDirectory)
  528. {
  529. int r;
  530. if(!getcwd(cp->RealWorkingDirectory, cp->RealWorkingDirectoryLength))
  531. {
  532. kwsysProcessCleanup(cp, 1);
  533. return;
  534. }
  535. /* Some platforms specify that the chdir call may be
  536. interrupted. Repeat the call until it finishes. */
  537. while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
  538. if(r < 0)
  539. {
  540. kwsysProcessCleanup(cp, 1);
  541. return;
  542. }
  543. }
  544. /* If not running a detached child, add this object to the global
  545. set of process objects that wish to be notified when a child
  546. exits. */
  547. if(!cp->OptionDetach)
  548. {
  549. if(!kwsysProcessesAdd(cp))
  550. {
  551. kwsysProcessCleanup(cp, 1);
  552. return;
  553. }
  554. }
  555. /* Setup the stderr pipe to be shared by all processes. */
  556. {
  557. /* Create the pipe. */
  558. int p[2];
  559. if(pipe(p) < 0)
  560. {
  561. kwsysProcessCleanup(cp, 1);
  562. return;
  563. }
  564. /* Store the pipe. */
  565. cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
  566. si.StdErr = p[1];
  567. /* Set close-on-exec flag on the pipe's ends. */
  568. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  569. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  570. {
  571. kwsysProcessCleanup(cp, 1);
  572. kwsysProcessCleanupDescriptor(&si.StdErr);
  573. return;
  574. }
  575. }
  576. /* Replace the stderr pipe with a file if requested. In this case
  577. the select call will report that stderr is closed immediately. */
  578. if(cp->PipeFileSTDERR)
  579. {
  580. if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
  581. {
  582. kwsysProcessCleanup(cp, 1);
  583. kwsysProcessCleanupDescriptor(&si.StdErr);
  584. return;
  585. }
  586. }
  587. /* Replace the stderr pipe with the parent's if requested. In this
  588. case the select call will report that stderr is closed
  589. immediately. */
  590. if(cp->PipeSharedSTDERR)
  591. {
  592. kwsysProcessCleanupDescriptor(&si.StdErr);
  593. si.StdErr = 2;
  594. }
  595. /* The timeout period starts now. */
  596. cp->StartTime = kwsysProcessTimeGetCurrent();
  597. cp->TimeoutTime.tv_sec = -1;
  598. cp->TimeoutTime.tv_usec = -1;
  599. /* Create the pipeline of processes. */
  600. {
  601. int readEnd = -1;
  602. for(i=0; i < cp->NumberOfCommands; ++i)
  603. {
  604. if(!kwsysProcessCreate(cp, i, &si, &readEnd))
  605. {
  606. kwsysProcessCleanup(cp, 1);
  607. /* Release resources that may have been allocated for this
  608. process before an error occurred. */
  609. kwsysProcessCleanupDescriptor(&readEnd);
  610. if(si.StdIn != 0)
  611. {
  612. kwsysProcessCleanupDescriptor(&si.StdIn);
  613. }
  614. if(si.StdOut != 1)
  615. {
  616. kwsysProcessCleanupDescriptor(&si.StdOut);
  617. }
  618. if(si.StdErr != 2)
  619. {
  620. kwsysProcessCleanupDescriptor(&si.StdErr);
  621. }
  622. kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
  623. kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
  624. return;
  625. }
  626. }
  627. /* Save a handle to the output pipe for the last process. */
  628. cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
  629. }
  630. /* The parent process does not need the output pipe write ends. */
  631. if(si.StdErr != 2)
  632. {
  633. kwsysProcessCleanupDescriptor(&si.StdErr);
  634. }
  635. /* Restore the working directory. */
  636. if(cp->RealWorkingDirectory)
  637. {
  638. /* Some platforms specify that the chdir call may be
  639. interrupted. Repeat the call until it finishes. */
  640. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  641. free(cp->RealWorkingDirectory);
  642. cp->RealWorkingDirectory = 0;
  643. }
  644. /* All the pipes are now open. */
  645. cp->PipesLeft = KWSYSPE_PIPE_COUNT;
  646. /* The process has now started. */
  647. cp->State = kwsysProcess_State_Executing;
  648. cp->Detached = cp->OptionDetach;
  649. }
  650. /*--------------------------------------------------------------------------*/
  651. kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
  652. {
  653. int i;
  654. /* Make sure a detached child process is running. */
  655. if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
  656. cp->TimeoutExpired || cp->Killed)
  657. {
  658. return;
  659. }
  660. /* Close any pipes that are still open. */
  661. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  662. {
  663. if(cp->PipeReadEnds[i] >= 0)
  664. {
  665. /* If the pipe was reported by the last call to select, we must
  666. read from it. Ignore the data. */
  667. if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  668. {
  669. /* We are handling this pipe now. Remove it from the set. */
  670. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  671. /* The pipe is ready to read without blocking. Keep trying to
  672. read until the operation is not interrupted. */
  673. while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
  674. KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
  675. }
  676. /* We are done reading from this pipe. */
  677. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  678. --cp->PipesLeft;
  679. }
  680. }
  681. /* We will not wait for exit, so cleanup now. */
  682. kwsysProcessCleanup(cp, 0);
  683. /* The process has been disowned. */
  684. cp->State = kwsysProcess_State_Disowned;
  685. }
  686. /*--------------------------------------------------------------------------*/
  687. int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
  688. double* userTimeout)
  689. {
  690. int i;
  691. int max = -1;
  692. kwsysProcessTimeNative* timeout = 0;
  693. kwsysProcessTimeNative timeoutLength;
  694. kwsysProcessTime timeoutTime;
  695. kwsysProcessTime userStartTime = {0, 0};
  696. int user = 0;
  697. int expired = 0;
  698. int pipeId = kwsysProcess_Pipe_None;
  699. int numReady = 0;
  700. /* Make sure we are executing a process. */
  701. if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
  702. cp->TimeoutExpired)
  703. {
  704. return kwsysProcess_Pipe_None;
  705. }
  706. /* Record the time at which user timeout period starts. */
  707. if(userTimeout)
  708. {
  709. userStartTime = kwsysProcessTimeGetCurrent();
  710. }
  711. /* Calculate the time at which a timeout will expire, and whether it
  712. is the user or process timeout. */
  713. user = kwsysProcessGetTimeoutTime(cp, userTimeout, &timeoutTime);
  714. /* Data can only be available when pipes are open. If the process
  715. is not running, cp->PipesLeft will be 0. */
  716. while(cp->PipesLeft > 0)
  717. {
  718. /* Check for any open pipes with data reported ready by the last
  719. call to select. According to "man select_tut" we must deal
  720. with all descriptors reported by a call to select before
  721. passing them to another select call. */
  722. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  723. {
  724. if(cp->PipeReadEnds[i] >= 0 &&
  725. FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  726. {
  727. int n;
  728. /* We are handling this pipe now. Remove it from the set. */
  729. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  730. /* The pipe is ready to read without blocking. Keep trying to
  731. read until the operation is not interrupted. */
  732. while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
  733. KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
  734. if(n > 0)
  735. {
  736. /* We have data on this pipe. */
  737. if(i == KWSYSPE_PIPE_SIGNAL)
  738. {
  739. /* A child process has terminated. */
  740. kwsysProcessDestroy(cp);
  741. }
  742. else if(data && length)
  743. {
  744. /* Report this data. */
  745. *data = cp->PipeBuffer;
  746. *length = n;
  747. switch(i)
  748. {
  749. case KWSYSPE_PIPE_STDOUT:
  750. pipeId = kwsysProcess_Pipe_STDOUT; break;
  751. case KWSYSPE_PIPE_STDERR:
  752. pipeId = kwsysProcess_Pipe_STDERR; break;
  753. };
  754. break;
  755. }
  756. }
  757. else
  758. {
  759. /* We are done reading from this pipe. */
  760. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  761. --cp->PipesLeft;
  762. }
  763. }
  764. }
  765. /* If we have data, break early. */
  766. if(pipeId)
  767. {
  768. break;
  769. }
  770. /* Make sure the set is empty (it should always be empty here
  771. anyway). */
  772. FD_ZERO(&cp->PipeSet);
  773. /* Setup a timeout if required. */
  774. if(timeoutTime.tv_sec < 0)
  775. {
  776. timeout = 0;
  777. }
  778. else
  779. {
  780. timeout = &timeoutLength;
  781. }
  782. if(kwsysProcessGetTimeoutLeft(&timeoutTime, user?userTimeout:0, &timeoutLength))
  783. {
  784. /* Timeout has already expired. */
  785. expired = 1;
  786. break;
  787. }
  788. /* Add the pipe reading ends that are still open. */
  789. max = -1;
  790. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  791. {
  792. if(cp->PipeReadEnds[i] >= 0)
  793. {
  794. FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
  795. if(cp->PipeReadEnds[i] > max)
  796. {
  797. max = cp->PipeReadEnds[i];
  798. }
  799. }
  800. }
  801. /* Make sure we have a non-empty set. */
  802. if(max < 0)
  803. {
  804. /* All pipes have closed. Child has terminated. */
  805. break;
  806. }
  807. /* Run select to block until data are available. Repeat call
  808. until it is not interrupted. */
  809. while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
  810. (errno == EINTR));
  811. /* Check result of select. */
  812. if(numReady == 0)
  813. {
  814. /* Select's timeout expired. */
  815. expired = 1;
  816. break;
  817. }
  818. else if(numReady < 0)
  819. {
  820. /* Select returned an error. Leave the error description in the
  821. pipe buffer. */
  822. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  823. /* Kill the children now. */
  824. kwsysProcess_Kill(cp);
  825. cp->Killed = 0;
  826. cp->SelectError = 1;
  827. }
  828. }
  829. /* Update the user timeout. */
  830. if(userTimeout)
  831. {
  832. kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
  833. kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
  834. userStartTime);
  835. double d = kwsysProcessTimeToDouble(difference);
  836. *userTimeout -= d;
  837. if(*userTimeout < 0)
  838. {
  839. *userTimeout = 0;
  840. }
  841. }
  842. /* Check what happened. */
  843. if(pipeId)
  844. {
  845. /* Data are ready on a pipe. */
  846. return pipeId;
  847. }
  848. else if(expired)
  849. {
  850. /* A timeout has expired. */
  851. if(user)
  852. {
  853. /* The user timeout has expired. It has no time left. */
  854. return kwsysProcess_Pipe_Timeout;
  855. }
  856. else
  857. {
  858. /* The process timeout has expired. Kill the children now. */
  859. kwsysProcess_Kill(cp);
  860. cp->Killed = 0;
  861. cp->TimeoutExpired = 1;
  862. return kwsysProcess_Pipe_None;
  863. }
  864. }
  865. else
  866. {
  867. /* No pipes are left open. */
  868. return kwsysProcess_Pipe_None;
  869. }
  870. }
  871. /*--------------------------------------------------------------------------*/
  872. int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
  873. {
  874. int status = 0;
  875. int prPipe = 0;
  876. /* Make sure we are executing a process. */
  877. if(!cp || cp->State != kwsysProcess_State_Executing)
  878. {
  879. return 1;
  880. }
  881. /* Wait for all the pipes to close. Ignore all data. */
  882. while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
  883. {
  884. if(prPipe == kwsysProcess_Pipe_Timeout)
  885. {
  886. return 0;
  887. }
  888. }
  889. /* Check if there was an error in one of the waitpid calls. */
  890. if(cp->State == kwsysProcess_State_Error)
  891. {
  892. /* The error message is already in its buffer. Tell
  893. kwsysProcessCleanup to not create it. */
  894. kwsysProcessCleanup(cp, 0);
  895. return 1;
  896. }
  897. /* Check whether the child reported an error invoking the process. */
  898. if(cp->SelectError)
  899. {
  900. /* The error message is already in its buffer. Tell
  901. kwsysProcessCleanup to not create it. */
  902. kwsysProcessCleanup(cp, 0);
  903. cp->State = kwsysProcess_State_Error;
  904. return 1;
  905. }
  906. /* Use the status of the last process in the pipeline. */
  907. status = cp->CommandExitCodes[cp->NumberOfCommands-1];
  908. /* Determine the outcome. */
  909. if(cp->Killed)
  910. {
  911. /* We killed the child. */
  912. cp->State = kwsysProcess_State_Killed;
  913. }
  914. else if(cp->TimeoutExpired)
  915. {
  916. /* The timeout expired. */
  917. cp->State = kwsysProcess_State_Expired;
  918. }
  919. else if(WIFEXITED(status))
  920. {
  921. /* The child exited normally. */
  922. cp->State = kwsysProcess_State_Exited;
  923. cp->ExitException = kwsysProcess_Exception_None;
  924. cp->ExitCode = status;
  925. cp->ExitValue = (int)WEXITSTATUS(status);
  926. }
  927. else if(WIFSIGNALED(status))
  928. {
  929. /* The child received an unhandled signal. */
  930. cp->State = kwsysProcess_State_Exception;
  931. cp->ExitCode = status;
  932. kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
  933. }
  934. else
  935. {
  936. /* Error getting the child return code. */
  937. strcpy(cp->ErrorMessage, "Error getting child return code.");
  938. cp->State = kwsysProcess_State_Error;
  939. }
  940. /* Normal cleanup. */
  941. kwsysProcessCleanup(cp, 0);
  942. return 1;
  943. }
  944. /*--------------------------------------------------------------------------*/
  945. void kwsysProcess_Kill(kwsysProcess* cp)
  946. {
  947. int i;
  948. /* Make sure we are executing a process. */
  949. if(!cp || cp->State != kwsysProcess_State_Executing)
  950. {
  951. return;
  952. }
  953. /* Close all the pipe read ends. Do this before killing the
  954. children because Cygwin has problems killing processes that are
  955. blocking to wait for writing to their output pipes. First close
  956. the child exit report pipe write end to avoid causing a SIGPIPE
  957. when the child terminates and our signal handler tries to report
  958. it. */
  959. kwsysProcessCleanupDescriptor(&cp->SignalPipe);
  960. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  961. {
  962. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  963. }
  964. cp->PipesLeft = 0;
  965. /* Kill the children. */
  966. cp->Killed = 1;
  967. for(i=0; i < cp->NumberOfCommands; ++i)
  968. {
  969. int status;
  970. if(cp->ForkPIDs[i])
  971. {
  972. /* Kill the child. */
  973. kwsysProcessKill(cp->ForkPIDs[i]);
  974. /* Reap the child. Keep trying until the call is not
  975. interrupted. */
  976. while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
  977. }
  978. }
  979. cp->CommandsLeft = 0;
  980. }
  981. /*--------------------------------------------------------------------------*/
  982. /* Initialize a process control structure for kwsysProcess_Execute. */
  983. static int kwsysProcessInitialize(kwsysProcess* cp)
  984. {
  985. int i;
  986. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  987. {
  988. cp->PipeReadEnds[i] = -1;
  989. }
  990. cp->SignalPipe = -1;
  991. cp->SelectError = 0;
  992. cp->StartTime.tv_sec = -1;
  993. cp->StartTime.tv_usec = -1;
  994. cp->TimeoutTime.tv_sec = -1;
  995. cp->TimeoutTime.tv_usec = -1;
  996. cp->TimeoutExpired = 0;
  997. cp->PipesLeft = 0;
  998. cp->CommandsLeft = 0;
  999. FD_ZERO(&cp->PipeSet);
  1000. cp->State = kwsysProcess_State_Starting;
  1001. cp->Killed = 0;
  1002. cp->ExitException = kwsysProcess_Exception_None;
  1003. cp->ExitCode = 1;
  1004. cp->ExitValue = 1;
  1005. cp->ErrorMessage[0] = 0;
  1006. strcpy(cp->ExitExceptionString, "No exception");
  1007. if(cp->ForkPIDs)
  1008. {
  1009. free(cp->ForkPIDs);
  1010. }
  1011. cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*cp->NumberOfCommands);
  1012. if(!cp->ForkPIDs)
  1013. {
  1014. return 0;
  1015. }
  1016. memset(cp->ForkPIDs, 0, sizeof(pid_t)*cp->NumberOfCommands);
  1017. if(cp->CommandExitCodes)
  1018. {
  1019. free(cp->CommandExitCodes);
  1020. }
  1021. cp->CommandExitCodes = (int*)malloc(sizeof(int)*cp->NumberOfCommands);
  1022. if(!cp->CommandExitCodes)
  1023. {
  1024. return 0;
  1025. }
  1026. memset(cp->CommandExitCodes, 0, sizeof(int)*cp->NumberOfCommands);
  1027. /* Allocate memory to save the real working directory. */
  1028. if ( cp->WorkingDirectory )
  1029. {
  1030. #if defined(MAXPATHLEN)
  1031. cp->RealWorkingDirectoryLength = MAXPATHLEN;
  1032. #elif defined(PATH_MAX)
  1033. cp->RealWorkingDirectoryLength = PATH_MAX;
  1034. #else
  1035. cp->RealWorkingDirectoryLength = 4096;
  1036. #endif
  1037. cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength);
  1038. if(!cp->RealWorkingDirectory)
  1039. {
  1040. return 0;
  1041. }
  1042. }
  1043. return 1;
  1044. }
  1045. /*--------------------------------------------------------------------------*/
  1046. /* Free all resources used by the given kwsysProcess instance that were
  1047. allocated by kwsysProcess_Execute. */
  1048. static void kwsysProcessCleanup(kwsysProcess* cp, int error)
  1049. {
  1050. int i;
  1051. if(error)
  1052. {
  1053. /* We are cleaning up due to an error. Report the error message
  1054. if one has not been provided already. */
  1055. if(cp->ErrorMessage[0] == 0)
  1056. {
  1057. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1058. }
  1059. /* Set the error state. */
  1060. cp->State = kwsysProcess_State_Error;
  1061. /* Kill any children already started. */
  1062. if(cp->ForkPIDs)
  1063. {
  1064. int status;
  1065. for(i=0; i < cp->NumberOfCommands; ++i)
  1066. {
  1067. if(cp->ForkPIDs[i])
  1068. {
  1069. /* Kill the child. */
  1070. kwsysProcessKill(cp->ForkPIDs[i]);
  1071. /* Reap the child. Keep trying until the call is not
  1072. interrupted. */
  1073. while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
  1074. (errno == EINTR));
  1075. }
  1076. }
  1077. }
  1078. /* Restore the working directory. */
  1079. if(cp->RealWorkingDirectory)
  1080. {
  1081. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  1082. }
  1083. }
  1084. /* If not creating a detached child, remove this object from the
  1085. global set of process objects that wish to be notified when a
  1086. child exits. */
  1087. if(!cp->OptionDetach)
  1088. {
  1089. kwsysProcessesRemove(cp);
  1090. }
  1091. /* Free memory. */
  1092. if(cp->ForkPIDs)
  1093. {
  1094. free(cp->ForkPIDs);
  1095. cp->ForkPIDs = 0;
  1096. }
  1097. if(cp->RealWorkingDirectory)
  1098. {
  1099. free(cp->RealWorkingDirectory);
  1100. cp->RealWorkingDirectory = 0;
  1101. }
  1102. /* Close pipe handles. */
  1103. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  1104. {
  1105. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  1106. }
  1107. }
  1108. /*--------------------------------------------------------------------------*/
  1109. /* Close the given file descriptor if it is open. Reset its value to -1. */
  1110. static void kwsysProcessCleanupDescriptor(int* pfd)
  1111. {
  1112. if(pfd && *pfd >= 0)
  1113. {
  1114. /* Keep trying to close until it is not interrupted by a
  1115. * signal. */
  1116. while((close(*pfd) < 0) && (errno == EINTR));
  1117. *pfd = -1;
  1118. }
  1119. }
  1120. /*--------------------------------------------------------------------------*/
  1121. static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
  1122. kwsysProcessCreateInformation* si, int* readEnd)
  1123. {
  1124. /* Setup the process's stdin. */
  1125. if(prIndex > 0)
  1126. {
  1127. si->StdIn = *readEnd;
  1128. *readEnd = 0;
  1129. }
  1130. else if(cp->PipeFileSTDIN)
  1131. {
  1132. /* Open a file for the child's stdin to read. */
  1133. si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
  1134. if(si->StdIn < 0)
  1135. {
  1136. return 0;
  1137. }
  1138. /* Set close-on-exec flag on the pipe's end. */
  1139. if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
  1140. {
  1141. return 0;
  1142. }
  1143. }
  1144. else if(cp->PipeSharedSTDIN)
  1145. {
  1146. si->StdIn = 0;
  1147. }
  1148. else
  1149. {
  1150. si->StdIn = -1;
  1151. }
  1152. /* Setup the process's stdout. */
  1153. {
  1154. /* Create the pipe. */
  1155. int p[2];
  1156. if(pipe(p) < 0)
  1157. {
  1158. return 0;
  1159. }
  1160. *readEnd = p[0];
  1161. si->StdOut = p[1];
  1162. /* Set close-on-exec flag on the pipe's ends. */
  1163. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  1164. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  1165. {
  1166. return 0;
  1167. }
  1168. }
  1169. /* Replace the stdout pipe with a file if requested. In this case
  1170. the select call will report that stdout is closed immediately. */
  1171. if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
  1172. {
  1173. if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
  1174. {
  1175. return 0;
  1176. }
  1177. }
  1178. /* Replace the stdout pipe with the parent's if requested. In this
  1179. case the select call will report that stderr is closed
  1180. immediately. */
  1181. if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
  1182. {
  1183. kwsysProcessCleanupDescriptor(&si->StdOut);
  1184. si->StdOut = 1;
  1185. }
  1186. /* Create the error reporting pipe. */
  1187. if(pipe(si->ErrorPipe) < 0)
  1188. {
  1189. return 0;
  1190. }
  1191. /* Set close-on-exec flag on the error pipe's write end. */
  1192. if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
  1193. {
  1194. return 0;
  1195. }
  1196. /* Fork off a child process. */
  1197. cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
  1198. if(cp->ForkPIDs[prIndex] < 0)
  1199. {
  1200. return 0;
  1201. }
  1202. if(cp->ForkPIDs[prIndex] == 0)
  1203. {
  1204. /* Close the read end of the error reporting pipe. */
  1205. close(si->ErrorPipe[0]);
  1206. /* Setup the stdin, stdout, and stderr pipes. */
  1207. if(si->StdIn > 0)
  1208. {
  1209. dup2(si->StdIn, 0);
  1210. }
  1211. else if(si->StdIn < 0)
  1212. {
  1213. close(0);
  1214. }
  1215. if(si->StdOut != 1)
  1216. {
  1217. dup2(si->StdOut, 1);
  1218. }
  1219. if(si->StdErr != 2)
  1220. {
  1221. dup2(si->StdErr, 2);
  1222. }
  1223. /* Clear the close-on-exec flag for stdin, stdout, and stderr.
  1224. All other pipe handles will be closed when exec succeeds. */
  1225. fcntl(0, F_SETFD, 0);
  1226. fcntl(1, F_SETFD, 0);
  1227. fcntl(2, F_SETFD, 0);
  1228. /* Restore all default signal handlers. */
  1229. kwsysProcessRestoreDefaultSignalHandlers();
  1230. /* Execute the real process. If successful, this does not return. */
  1231. execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
  1232. /* Failure. Report error to parent and terminate. */
  1233. kwsysProcessChildErrorExit(si->ErrorPipe[1]);
  1234. }
  1235. /* A child has been created. */
  1236. ++cp->CommandsLeft;
  1237. /* We are done with the error reporting pipe write end. */
  1238. kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
  1239. /* Block until the child's exec call succeeds and closes the error
  1240. pipe or writes data to the pipe to report an error. */
  1241. {
  1242. int total = 0;
  1243. int n = 1;
  1244. /* Read the entire error message up to the length of our buffer. */
  1245. while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
  1246. {
  1247. /* Keep trying to read until the operation is not interrupted. */
  1248. while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
  1249. KWSYSPE_PIPE_BUFFER_SIZE-total)) < 0) &&
  1250. (errno == EINTR));
  1251. if(n > 0)
  1252. {
  1253. total += n;
  1254. }
  1255. }
  1256. /* We are done with the error reporting pipe read end. */
  1257. kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
  1258. if(total > 0)
  1259. {
  1260. /* The child failed to execute the process. */
  1261. return 0;
  1262. }
  1263. }
  1264. /* Successfully created this child process. */
  1265. if(prIndex > 0 || si->StdIn > 0)
  1266. {
  1267. /* The parent process does not need the input pipe read end. */
  1268. kwsysProcessCleanupDescriptor(&si->StdIn);
  1269. }
  1270. /* The parent process does not need the output pipe write ends. */
  1271. if(si->StdOut != 1)
  1272. {
  1273. kwsysProcessCleanupDescriptor(&si->StdOut);
  1274. }
  1275. return 1;
  1276. }
  1277. /*--------------------------------------------------------------------------*/
  1278. static void kwsysProcessDestroy(kwsysProcess* cp)
  1279. {
  1280. /* A child process has terminated. Reap it if it is one handled by
  1281. this object. */
  1282. int i;
  1283. for(i=0; i < cp->NumberOfCommands; ++i)
  1284. {
  1285. if(cp->ForkPIDs[i])
  1286. {
  1287. int result;
  1288. while(((result = waitpid(cp->ForkPIDs[i],
  1289. &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
  1290. (errno == EINTR));
  1291. if(result > 0)
  1292. {
  1293. /* This child has termianted. */
  1294. cp->ForkPIDs[i] = 0;
  1295. if(--cp->CommandsLeft == 0)
  1296. {
  1297. /* All children have terminated. Close the signal pipe
  1298. write end so that no more notifications are sent to this
  1299. object. */
  1300. kwsysProcessCleanupDescriptor(&cp->SignalPipe);
  1301. /* TODO: Once the children have terminated, switch
  1302. WaitForData to use a non-blocking read to get the
  1303. rest of the data from the pipe. This is needed when
  1304. grandchildren keep the output pipes open. */
  1305. }
  1306. }
  1307. else if(result < 0 && cp->State != kwsysProcess_State_Error)
  1308. {
  1309. /* Unexpected error. Report the first time this happens. */
  1310. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1311. cp->State = kwsysProcess_State_Error;
  1312. }
  1313. }
  1314. }
  1315. }
  1316. /*--------------------------------------------------------------------------*/
  1317. static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
  1318. {
  1319. int fout;
  1320. if(!name)
  1321. {
  1322. return 1;
  1323. }
  1324. /* Close the existing descriptor. */
  1325. kwsysProcessCleanupDescriptor(p);
  1326. /* Open a file for the pipe to write (permissions 644). */
  1327. if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC,
  1328. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
  1329. {
  1330. return 0;
  1331. }
  1332. /* Set close-on-exec flag on the pipe's end. */
  1333. if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
  1334. {
  1335. return 0;
  1336. }
  1337. /* Assign the replacement descriptor. */
  1338. *p = fout;
  1339. return 1;
  1340. }
  1341. /*--------------------------------------------------------------------------*/
  1342. /* Get the time at which either the process or user timeout will
  1343. expire. Returns 1 if the user timeout is first, and 0 otherwise. */
  1344. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  1345. kwsysProcessTime* timeoutTime)
  1346. {
  1347. /* The first time this is called, we need to calculate the time at
  1348. which the child will timeout. */
  1349. if(cp->Timeout && cp->TimeoutTime.tv_sec < 0)
  1350. {
  1351. kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
  1352. cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
  1353. }
  1354. /* Start with process timeout. */
  1355. *timeoutTime = cp->TimeoutTime;
  1356. /* Check if the user timeout is earlier. */
  1357. if(userTimeout)
  1358. {
  1359. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1360. kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
  1361. kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
  1362. userTimeoutLength);
  1363. if(timeoutTime->tv_sec < 0 ||
  1364. kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
  1365. {
  1366. *timeoutTime = userTimeoutTime;
  1367. return 1;
  1368. }
  1369. }
  1370. return 0;
  1371. }
  1372. /*--------------------------------------------------------------------------*/
  1373. /* Get the length of time before the given timeout time arrives.
  1374. Returns 1 if the time has already arrived, and 0 otherwise. */
  1375. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  1376. double* userTimeout,
  1377. kwsysProcessTimeNative* timeoutLength)
  1378. {
  1379. if(timeoutTime->tv_sec < 0)
  1380. {
  1381. /* No timeout time has been requested. */
  1382. return 0;
  1383. }
  1384. else
  1385. {
  1386. /* Calculate the remaining time. */
  1387. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1388. kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
  1389. currentTime);
  1390. if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
  1391. {
  1392. /* Caller has explicitly requested a zero timeout. */
  1393. timeLeft.tv_sec = 0;
  1394. timeLeft.tv_usec = 0;
  1395. }
  1396. if(timeLeft.tv_sec < 0)
  1397. {
  1398. /* Timeout has already expired. */
  1399. return 1;
  1400. }
  1401. else
  1402. {
  1403. /* There is some time left. */
  1404. timeoutLength->tv_sec = timeLeft.tv_sec;
  1405. timeoutLength->tv_usec = timeLeft.tv_usec;
  1406. return 0;
  1407. }
  1408. }
  1409. }
  1410. /*--------------------------------------------------------------------------*/
  1411. static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
  1412. {
  1413. kwsysProcessTime current;
  1414. kwsysProcessTimeNative current_native;
  1415. gettimeofday(&current_native, 0);
  1416. current.tv_sec = (long)current_native.tv_sec;
  1417. current.tv_usec = (long)current_native.tv_usec;
  1418. return current;
  1419. }
  1420. /*--------------------------------------------------------------------------*/
  1421. static double kwsysProcessTimeToDouble(kwsysProcessTime t)
  1422. {
  1423. return (double)t.tv_sec + t.tv_usec*0.000001;
  1424. }
  1425. /*--------------------------------------------------------------------------*/
  1426. static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
  1427. {
  1428. kwsysProcessTime t;
  1429. t.tv_sec = (long)d;
  1430. t.tv_usec = (long)((d-t.tv_sec)*1000000);
  1431. return t;
  1432. }
  1433. /*--------------------------------------------------------------------------*/
  1434. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
  1435. {
  1436. return ((in1.tv_sec < in2.tv_sec) ||
  1437. ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
  1438. }
  1439. /*--------------------------------------------------------------------------*/
  1440. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
  1441. {
  1442. kwsysProcessTime out;
  1443. out.tv_sec = in1.tv_sec + in2.tv_sec;
  1444. out.tv_usec = in1.tv_usec + in2.tv_usec;
  1445. if(out.tv_usec > 1000000)
  1446. {
  1447. out.tv_usec -= 1000000;
  1448. out.tv_sec += 1;
  1449. }
  1450. return out;
  1451. }
  1452. /*--------------------------------------------------------------------------*/
  1453. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
  1454. {
  1455. kwsysProcessTime out;
  1456. out.tv_sec = in1.tv_sec - in2.tv_sec;
  1457. out.tv_usec = in1.tv_usec - in2.tv_usec;
  1458. if(out.tv_usec < 0)
  1459. {
  1460. out.tv_usec += 1000000;
  1461. out.tv_sec -= 1;
  1462. }
  1463. return out;
  1464. }
  1465. /*--------------------------------------------------------------------------*/
  1466. #define KWSYSPE_CASE(type, str) \
  1467. cp->ExitException = kwsysProcess_Exception_##type; \
  1468. strcpy(cp->ExitExceptionString, str)
  1469. static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
  1470. {
  1471. switch (sig)
  1472. {
  1473. #ifdef SIGSEGV
  1474. case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
  1475. #endif
  1476. #ifdef SIGBUS
  1477. # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
  1478. case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
  1479. # endif
  1480. #endif
  1481. #ifdef SIGFPE
  1482. case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
  1483. #endif
  1484. #ifdef SIGILL
  1485. case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
  1486. #endif
  1487. #ifdef SIGINT
  1488. case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
  1489. #endif
  1490. #ifdef SIGABRT
  1491. case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
  1492. #endif
  1493. #ifdef SIGKILL
  1494. case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
  1495. #endif
  1496. #ifdef SIGTERM
  1497. case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
  1498. #endif
  1499. #ifdef SIGHUP
  1500. case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
  1501. #endif
  1502. #ifdef SIGQUIT
  1503. case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
  1504. #endif
  1505. #ifdef SIGTRAP
  1506. case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
  1507. #endif
  1508. #ifdef SIGIOT
  1509. # if !defined(SIGABRT) || SIGIOT != SIGABRT
  1510. case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
  1511. # endif
  1512. #endif
  1513. #ifdef SIGUSR1
  1514. case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
  1515. #endif
  1516. #ifdef SIGUSR2
  1517. case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
  1518. #endif
  1519. #ifdef SIGPIPE
  1520. case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
  1521. #endif
  1522. #ifdef SIGALRM
  1523. case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
  1524. #endif
  1525. #ifdef SIGSTKFLT
  1526. case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
  1527. #endif
  1528. #ifdef SIGCHLD
  1529. case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
  1530. #elif defined(SIGCLD)
  1531. case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
  1532. #endif
  1533. #ifdef SIGCONT
  1534. case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
  1535. #endif
  1536. #ifdef SIGSTOP
  1537. case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
  1538. #endif
  1539. #ifdef SIGTSTP
  1540. case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
  1541. #endif
  1542. #ifdef SIGTTIN
  1543. case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
  1544. #endif
  1545. #ifdef SIGTTOU
  1546. case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
  1547. #endif
  1548. #ifdef SIGURG
  1549. case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
  1550. #endif
  1551. #ifdef SIGXCPU
  1552. case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
  1553. #endif
  1554. #ifdef SIGXFSZ
  1555. case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
  1556. #endif
  1557. #ifdef SIGVTALRM
  1558. case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
  1559. #endif
  1560. #ifdef SIGPROF
  1561. case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
  1562. #endif
  1563. #ifdef SIGWINCH
  1564. case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
  1565. #endif
  1566. #ifdef SIGPOLL
  1567. case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
  1568. #endif
  1569. #ifdef SIGIO
  1570. # if !defined(SIGPOLL) || SIGIO != SIGPOLL
  1571. case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
  1572. # endif
  1573. #endif
  1574. #ifdef SIGPWR
  1575. case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
  1576. #endif
  1577. #ifdef SIGSYS
  1578. case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
  1579. #endif
  1580. #ifdef SIGUNUSED
  1581. # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
  1582. case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
  1583. # endif
  1584. #endif
  1585. default:
  1586. cp->ExitException = kwsysProcess_Exception_Other;
  1587. sprintf(cp->ExitExceptionString, "Signal %d", sig);
  1588. break;
  1589. }
  1590. }
  1591. #undef KWSYSPE_CASE
  1592. /*--------------------------------------------------------------------------*/
  1593. /* When the child process encounters an error before its program is
  1594. invoked, this is called to report the error to the parent and
  1595. exit. */
  1596. static void kwsysProcessChildErrorExit(int errorPipe)
  1597. {
  1598. /* Construct the error message. */
  1599. char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
  1600. strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1601. /* Report the error to the parent through the special pipe. */
  1602. write(errorPipe, buffer, strlen(buffer));
  1603. /* Terminate without cleanup. */
  1604. _exit(1);
  1605. }
  1606. /*--------------------------------------------------------------------------*/
  1607. /* Restores all signal handlers to their default values. */
  1608. static void kwsysProcessRestoreDefaultSignalHandlers(void)
  1609. {
  1610. struct sigaction act;
  1611. memset(&act, 0, sizeof(struct sigaction));
  1612. act.sa_handler = SIG_DFL;
  1613. #ifdef SIGHUP
  1614. sigaction(SIGHUP, &act, 0);
  1615. #endif
  1616. #ifdef SIGINT
  1617. sigaction(SIGINT, &act, 0);
  1618. #endif
  1619. #ifdef SIGQUIT
  1620. sigaction(SIGQUIT, &act, 0);
  1621. #endif
  1622. #ifdef SIGILL
  1623. sigaction(SIGILL, &act, 0);
  1624. #endif
  1625. #ifdef SIGTRAP
  1626. sigaction(SIGTRAP, &act, 0);
  1627. #endif
  1628. #ifdef SIGABRT
  1629. sigaction(SIGABRT, &act, 0);
  1630. #endif
  1631. #ifdef SIGIOT
  1632. sigaction(SIGIOT, &act, 0);
  1633. #endif
  1634. #ifdef SIGBUS
  1635. sigaction(SIGBUS, &act, 0);
  1636. #endif
  1637. #ifdef SIGFPE
  1638. sigaction(SIGFPE, &act, 0);
  1639. #endif
  1640. #ifdef SIGUSR1
  1641. sigaction(SIGUSR1, &act, 0);
  1642. #endif
  1643. #ifdef SIGSEGV
  1644. sigaction(SIGSEGV, &act, 0);
  1645. #endif
  1646. #ifdef SIGUSR2
  1647. sigaction(SIGUSR2, &act, 0);
  1648. #endif
  1649. #ifdef SIGPIPE
  1650. sigaction(SIGPIPE, &act, 0);
  1651. #endif
  1652. #ifdef SIGALRM
  1653. sigaction(SIGALRM, &act, 0);
  1654. #endif
  1655. #ifdef SIGTERM
  1656. sigaction(SIGTERM, &act, 0);
  1657. #endif
  1658. #ifdef SIGSTKFLT
  1659. sigaction(SIGSTKFLT, &act, 0);
  1660. #endif
  1661. #ifdef SIGCLD
  1662. sigaction(SIGCLD, &act, 0);
  1663. #endif
  1664. #ifdef SIGCHLD
  1665. sigaction(SIGCHLD, &act, 0);
  1666. #endif
  1667. #ifdef SIGCONT
  1668. sigaction(SIGCONT, &act, 0);
  1669. #endif
  1670. #ifdef SIGTSTP
  1671. sigaction(SIGTSTP, &act, 0);
  1672. #endif
  1673. #ifdef SIGTTIN
  1674. sigaction(SIGTTIN, &act, 0);
  1675. #endif
  1676. #ifdef SIGTTOU
  1677. sigaction(SIGTTOU, &act, 0);
  1678. #endif
  1679. #ifdef SIGURG
  1680. sigaction(SIGURG, &act, 0);
  1681. #endif
  1682. #ifdef SIGXCPU
  1683. sigaction(SIGXCPU, &act, 0);
  1684. #endif
  1685. #ifdef SIGXFSZ
  1686. sigaction(SIGXFSZ, &act, 0);
  1687. #endif
  1688. #ifdef SIGVTALRM
  1689. sigaction(SIGVTALRM, &act, 0);
  1690. #endif
  1691. #ifdef SIGPROF
  1692. sigaction(SIGPROF, &act, 0);
  1693. #endif
  1694. #ifdef SIGWINCH
  1695. sigaction(SIGWINCH, &act, 0);
  1696. #endif
  1697. #ifdef SIGPOLL
  1698. sigaction(SIGPOLL, &act, 0);
  1699. #endif
  1700. #ifdef SIGIO
  1701. sigaction(SIGIO, &act, 0);
  1702. #endif
  1703. #ifdef SIGPWR
  1704. sigaction(SIGPWR, &act, 0);
  1705. #endif
  1706. #ifdef SIGSYS
  1707. sigaction(SIGSYS, &act, 0);
  1708. #endif
  1709. #ifdef SIGUNUSED
  1710. sigaction(SIGUNUSED, &act, 0);
  1711. #endif
  1712. }
  1713. /*--------------------------------------------------------------------------*/
  1714. static pid_t kwsysProcessFork(kwsysProcess* cp,
  1715. kwsysProcessCreateInformation* si)
  1716. {
  1717. /* Create a detached process if requested. */
  1718. if(cp->OptionDetach)
  1719. {
  1720. /* Create an intermediate process. */
  1721. pid_t middle_pid = fork();
  1722. if(middle_pid < 0)
  1723. {
  1724. /* Fork failed. Return as if we were not detaching. */
  1725. return middle_pid;
  1726. }
  1727. else if(middle_pid == 0)
  1728. {
  1729. /* This is the intermediate process. Create the real child. */
  1730. pid_t child_pid = fork();
  1731. if(child_pid == 0)
  1732. {
  1733. /* This is the real child process. There is nothing to do here. */
  1734. return 0;
  1735. }
  1736. else
  1737. {
  1738. /* Use the error pipe to report the pid to the real parent. */
  1739. while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
  1740. (errno == EINTR));
  1741. /* Exit without cleanup. The parent holds all resources. */
  1742. _exit(0);
  1743. return 0; /* Never reached, but avoids SunCC warning. */
  1744. }
  1745. }
  1746. else
  1747. {
  1748. /* This is the original parent process. The intermediate
  1749. process will use the error pipe to report the pid of the
  1750. detached child. */
  1751. pid_t child_pid;
  1752. int status;
  1753. while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
  1754. (errno == EINTR));
  1755. /* Wait for the intermediate process to exit and clean it up. */
  1756. while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
  1757. return child_pid;
  1758. }
  1759. }
  1760. else
  1761. {
  1762. /* Not creating a detached process. Use normal fork. */
  1763. return fork();
  1764. }
  1765. }
  1766. /*--------------------------------------------------------------------------*/
  1767. /* We try to obtain process information by invoking the ps command.
  1768. Here we define the command to call on each platform and the
  1769. corresponding parsing format string. The parsing format should
  1770. have two integers to store: the pid and then the ppid. */
  1771. #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
  1772. # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
  1773. # define KWSYSPE_PS_FORMAT "%d %d\n"
  1774. #elif defined(__hpux) || defined(__sparc) || defined(__sgi) || defined(_AIX)
  1775. # define KWSYSPE_PS_COMMAND "ps -ef"
  1776. # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
  1777. #elif defined(__CYGWIN__)
  1778. # define KWSYSPE_PS_COMMAND "ps aux"
  1779. # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
  1780. #endif
  1781. /*--------------------------------------------------------------------------*/
  1782. static void kwsysProcessKill(pid_t process_id)
  1783. {
  1784. #if defined(__linux__) || defined(__CYGWIN__)
  1785. DIR* procdir;
  1786. #endif
  1787. /* Suspend the process to be sure it will not create more children. */
  1788. kill(process_id, SIGSTOP);
  1789. /* Kill all children if we can find them. */
  1790. #if defined(__linux__) || defined(__CYGWIN__)
  1791. /* First try using the /proc filesystem. */
  1792. if((procdir = opendir("/proc")) != NULL)
  1793. {
  1794. #if defined(MAXPATHLEN)
  1795. char fname[MAXPATHLEN];
  1796. #elif defined(PATH_MAX)
  1797. char fname[PATH_MAX];
  1798. #else
  1799. char fname[4096];
  1800. #endif
  1801. char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
  1802. struct dirent* d;
  1803. /* Each process has a directory in /proc whose name is the pid.
  1804. Within this directory is a file called stat that has the
  1805. following format:
  1806. pid (command line) status ppid ...
  1807. We want to get the ppid for all processes. Those that have
  1808. process_id as their parent should be recursively killed. */
  1809. for(d = readdir(procdir); d; d = readdir(procdir))
  1810. {
  1811. int pid;
  1812. if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
  1813. {
  1814. struct stat finfo;
  1815. sprintf(fname, "/proc/%d/stat", pid);
  1816. if(stat(fname, &finfo) == 0)
  1817. {
  1818. FILE* f = fopen(fname, "r");
  1819. if(f)
  1820. {
  1821. int nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
  1822. buffer[nread] = '\0';
  1823. if(nread > 0)
  1824. {
  1825. const char* rparen = strrchr(buffer, ')');
  1826. int ppid;
  1827. if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
  1828. {
  1829. if(ppid == process_id)
  1830. {
  1831. /* Recursively kill this child and its children. */
  1832. kwsysProcessKill(pid);
  1833. }
  1834. }
  1835. }
  1836. fclose(f);
  1837. }
  1838. }
  1839. }
  1840. }
  1841. closedir(procdir);
  1842. }
  1843. else
  1844. #endif
  1845. {
  1846. #if defined(KWSYSPE_PS_COMMAND)
  1847. /* Try running "ps" to get the process information. */
  1848. FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
  1849. /* Make sure the process started and provided a valid header. */
  1850. if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
  1851. {
  1852. /* Look for processes whose parent is the process being killed. */
  1853. int pid, ppid;
  1854. while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
  1855. {
  1856. if(ppid == process_id)
  1857. {
  1858. /* Recursively kill this child aned its children. */
  1859. kwsysProcessKill(pid);
  1860. }
  1861. }
  1862. }
  1863. /* We are done with the ps process. */
  1864. if(ps)
  1865. {
  1866. pclose(ps);
  1867. }
  1868. #endif
  1869. }
  1870. /* Kill the process. */
  1871. kill(process_id, SIGKILL);
  1872. }
  1873. /*--------------------------------------------------------------------------*/
  1874. /* Global set of executing processes for use by the signal handler.
  1875. This global instance will be zero-initialized by the compiler. */
  1876. typedef struct kwsysProcessInstances_s
  1877. {
  1878. int Count;
  1879. int Size;
  1880. kwsysProcess** Processes;
  1881. } kwsysProcessInstances;
  1882. static kwsysProcessInstances kwsysProcesses;
  1883. /* The old SIGCHLD handler. */
  1884. static struct sigaction kwsysProcessesOldSigChldAction;
  1885. /*--------------------------------------------------------------------------*/
  1886. static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
  1887. {
  1888. /* Block SIGCHLD while we update the set of pipes to check.
  1889. TODO: sigprocmask is undefined for threaded apps. See
  1890. pthread_sigmask. */
  1891. sigset_t newset;
  1892. sigset_t oldset;
  1893. sigemptyset(&newset);
  1894. sigaddset(&newset, SIGCHLD);
  1895. sigprocmask(SIG_BLOCK, &newset, &oldset);
  1896. /* Store the new set in that seen by the signal handler. */
  1897. kwsysProcesses = *newProcesses;
  1898. /* Restore the signal mask to the previous setting. */
  1899. sigprocmask(SIG_SETMASK, &oldset, 0);
  1900. }
  1901. /*--------------------------------------------------------------------------*/
  1902. static int kwsysProcessesAdd(kwsysProcess* cp)
  1903. {
  1904. /* Create a pipe through which the signal handler can notify the
  1905. given process object that a child has exited. */
  1906. {
  1907. /* Create the pipe. */
  1908. int oldfl[2];
  1909. int p[2];
  1910. if(pipe(p) < 0)
  1911. {
  1912. return 0;
  1913. }
  1914. /* Store the pipes now to be sure they are cleaned up later. */
  1915. cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
  1916. cp->SignalPipe = p[1];
  1917. /* Switch the pipe to non-blocking mode so that reading a byte can
  1918. be an atomic test-and-set. */
  1919. if((oldfl[0] = fcntl(p[0], F_GETFL) < 0) ||
  1920. (oldfl[1] = fcntl(p[1], F_GETFL) < 0) ||
  1921. (fcntl(p[0], F_SETFL, oldfl[0] | O_NONBLOCK) < 0) ||
  1922. (fcntl(p[1], F_SETFL, oldfl[1] | O_NONBLOCK) < 0))
  1923. {
  1924. return 0;
  1925. }
  1926. /* The children do not need this pipe. Set close-on-exec flag on
  1927. the pipe's ends. */
  1928. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  1929. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  1930. {
  1931. return 0;
  1932. }
  1933. }
  1934. /* Attempt to add the given signal pipe to the signal handler set. */
  1935. {
  1936. /* Make sure there is enough space for the new signal pipe. */
  1937. kwsysProcessInstances oldProcesses = kwsysProcesses;
  1938. kwsysProcessInstances newProcesses = oldProcesses;
  1939. if(oldProcesses.Count == oldProcesses.Size)
  1940. {
  1941. /* Start with enough space for a small number of process instances
  1942. and double the size each time more is needed. */
  1943. newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
  1944. /* Try allocating the new block of memory. */
  1945. if((newProcesses.Processes = ((kwsysProcess**)
  1946. malloc(newProcesses.Size*
  1947. sizeof(kwsysProcess*)))))
  1948. {
  1949. /* Copy the old pipe set to the new memory. */
  1950. if(oldProcesses.Count > 0)
  1951. {
  1952. memcpy(newProcesses.Processes, oldProcesses.Processes,
  1953. (oldProcesses.Count * sizeof(kwsysProcess*)));
  1954. }
  1955. }
  1956. else
  1957. {
  1958. /* Failed to allocate memory for the new signal pipe set. */
  1959. return 0;
  1960. }
  1961. }
  1962. /* Append the new signal pipe to the set. */
  1963. newProcesses.Processes[newProcesses.Count++] = cp;
  1964. /* Store the new set in that seen by the signal handler. */
  1965. kwsysProcessesUpdate(&newProcesses);
  1966. /* Free the original pipes if new ones were allocated. */
  1967. if(newProcesses.Processes != oldProcesses.Processes)
  1968. {
  1969. free(oldProcesses.Processes);
  1970. }
  1971. /* If this is the first process, enable the signal handler. */
  1972. if(newProcesses.Count == 1)
  1973. {
  1974. /* Install our handler for SIGCHLD. Repeat call until it is not
  1975. interrupted. */
  1976. struct sigaction newSigChldAction;
  1977. memset(&newSigChldAction, 0, sizeof(struct sigaction));
  1978. newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
  1979. newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_RESTART | SA_SIGINFO;
  1980. while((sigaction(SIGCHLD, &newSigChldAction,
  1981. &kwsysProcessesOldSigChldAction) < 0) &&
  1982. (errno == EINTR));
  1983. }
  1984. }
  1985. return 1;
  1986. }
  1987. /*--------------------------------------------------------------------------*/
  1988. static void kwsysProcessesRemove(kwsysProcess* cp)
  1989. {
  1990. /* Attempt to remove the given signal pipe from the signal handler set. */
  1991. {
  1992. /* Find the given process in the set. */
  1993. kwsysProcessInstances newProcesses = kwsysProcesses;
  1994. int i;
  1995. for(i=0; i < newProcesses.Count; ++i)
  1996. {
  1997. if(newProcesses.Processes[i] == cp)
  1998. {
  1999. break;
  2000. }
  2001. }
  2002. if(i < newProcesses.Count)
  2003. {
  2004. /* Remove the process from the set. */
  2005. --newProcesses.Count;
  2006. for(; i < newProcesses.Count; ++i)
  2007. {
  2008. newProcesses.Processes[i] = newProcesses.Processes[i+1];
  2009. }
  2010. /* If this was the last process, disable the signal handler. */
  2011. if(newProcesses.Count == 0)
  2012. {
  2013. /* Restore the SIGCHLD handler. Repeat call until it is not
  2014. interrupted. */
  2015. while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
  2016. (errno == EINTR));
  2017. /* Free the table of process pointers since it is now empty.
  2018. This is safe because the signal handler has been removed. */
  2019. newProcesses.Size = 0;
  2020. free(newProcesses.Processes);
  2021. newProcesses.Processes = 0;
  2022. }
  2023. /* Store the new set in that seen by the signal handler. */
  2024. kwsysProcessesUpdate(&newProcesses);
  2025. }
  2026. }
  2027. /* Close the pipe through which the signal handler may have notified
  2028. the given process object that a child has exited. */
  2029. kwsysProcessCleanupDescriptor(&cp->SignalPipe);
  2030. }
  2031. /*--------------------------------------------------------------------------*/
  2032. static void kwsysProcessesSignalHandler(int signum, siginfo_t* info,
  2033. void* ucontext)
  2034. {
  2035. /* Signal all process objects that a child has terminated. */
  2036. int i;
  2037. (void)signum;
  2038. (void)info;
  2039. (void)ucontext;
  2040. for(i=0; i < kwsysProcesses.Count; ++i)
  2041. {
  2042. /* Set the pipe in a signalled state. */
  2043. char buf = 1;
  2044. kwsysProcess* cp = kwsysProcesses.Processes[i];
  2045. read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
  2046. write(cp->SignalPipe, &buf, 1);
  2047. }
  2048. }
  2049. /*--------------------------------------------------------------------------*/
  2050. static int kwsysProcessAppendByte(char* local,
  2051. char** begin, char** end,
  2052. int* size, char c)
  2053. {
  2054. /* Allocate space for the character. */
  2055. if((*end - *begin) >= *size)
  2056. {
  2057. int length = *end - *begin;
  2058. char* newBuffer = (char*)malloc(*size*2);
  2059. if(!newBuffer)
  2060. {
  2061. return 0;
  2062. }
  2063. memcpy(newBuffer, *begin, length*sizeof(char));
  2064. if(*begin != local)
  2065. {
  2066. free(*begin);
  2067. }
  2068. *begin = newBuffer;
  2069. *end = *begin + length;
  2070. *size *= 2;
  2071. }
  2072. /* Store the character. */
  2073. *(*end)++ = c;
  2074. return 1;
  2075. }
  2076. /*--------------------------------------------------------------------------*/
  2077. static int kwsysProcessAppendArgument(char** local,
  2078. char*** begin, char*** end,
  2079. int* size,
  2080. char* arg_local,
  2081. char** arg_begin, char** arg_end,
  2082. int* arg_size)
  2083. {
  2084. /* Append a null-terminator to the argument string. */
  2085. if(!kwsysProcessAppendByte(arg_local, arg_begin, arg_end, arg_size, '\0'))
  2086. {
  2087. return 0;
  2088. }
  2089. /* Allocate space for the argument pointer. */
  2090. if((*end - *begin) >= *size)
  2091. {
  2092. int length = *end - *begin;
  2093. char** newPointers = (char**)malloc(*size*2*sizeof(char*));
  2094. if(!newPointers)
  2095. {
  2096. return 0;
  2097. }
  2098. memcpy(newPointers, *begin, length*sizeof(char*));
  2099. if(*begin != local)
  2100. {
  2101. free(*begin);
  2102. }
  2103. *begin = newPointers;
  2104. *end = *begin + length;
  2105. *size *= 2;
  2106. }
  2107. /* Allocate space for the argument string. */
  2108. **end = (char*)malloc(*arg_end - *arg_begin);
  2109. if(!**end)
  2110. {
  2111. return 0;
  2112. }
  2113. /* Store the argument in the command array. */
  2114. memcpy(**end, *arg_begin, *arg_end - *arg_begin);
  2115. ++(*end);
  2116. /* Reset the argument to be empty. */
  2117. *arg_end = *arg_begin;
  2118. return 1;
  2119. }
  2120. /*--------------------------------------------------------------------------*/
  2121. #define KWSYSPE_LOCAL_BYTE_COUNT 1024
  2122. #define KWSYSPE_LOCAL_ARGS_COUNT 32
  2123. static char** kwsysProcessParseVerbatimCommand(const char* command)
  2124. {
  2125. /* Create a buffer for argument pointers during parsing. */
  2126. char* local_pointers[KWSYSPE_LOCAL_ARGS_COUNT];
  2127. int pointers_size = KWSYSPE_LOCAL_ARGS_COUNT;
  2128. char** pointer_begin = local_pointers;
  2129. char** pointer_end = pointer_begin;
  2130. /* Create a buffer for argument strings during parsing. */
  2131. char local_buffer[KWSYSPE_LOCAL_BYTE_COUNT];
  2132. int buffer_size = KWSYSPE_LOCAL_BYTE_COUNT;
  2133. char* buffer_begin = local_buffer;
  2134. char* buffer_end = buffer_begin;
  2135. /* Parse the command string. Try to behave like a UNIX shell. */
  2136. char** newCommand = 0;
  2137. const char* c = command;
  2138. int in_argument = 0;
  2139. int in_escape = 0;
  2140. int in_single = 0;
  2141. int in_double = 0;
  2142. int failed = 0;
  2143. for(;*c; ++c)
  2144. {
  2145. if(in_escape)
  2146. {
  2147. /* This character is escaped so do no special handling. */
  2148. if(!in_argument)
  2149. {
  2150. in_argument = 1;
  2151. }
  2152. if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
  2153. &buffer_end, &buffer_size, *c))
  2154. {
  2155. failed = 1;
  2156. break;
  2157. }
  2158. in_escape = 0;
  2159. }
  2160. else if(*c == '\\' && !in_single)
  2161. {
  2162. /* The next character should be escaped. */
  2163. in_escape = 1;
  2164. }
  2165. else if(*c == '\'' && !in_double)
  2166. {
  2167. /* Enter or exit single-quote state. */
  2168. if(in_single)
  2169. {
  2170. in_single = 0;
  2171. }
  2172. else
  2173. {
  2174. in_single = 1;
  2175. if(!in_argument)
  2176. {
  2177. in_argument = 1;
  2178. }
  2179. }
  2180. }
  2181. else if(*c == '"' && !in_single)
  2182. {
  2183. /* Enter or exit double-quote state. */
  2184. if(in_double)
  2185. {
  2186. in_double = 0;
  2187. }
  2188. else
  2189. {
  2190. in_double = 1;
  2191. if(!in_argument)
  2192. {
  2193. in_argument = 1;
  2194. }
  2195. }
  2196. }
  2197. else if(isspace(*c))
  2198. {
  2199. if(in_argument)
  2200. {
  2201. if(in_single || in_double)
  2202. {
  2203. /* This space belongs to a quoted argument. */
  2204. if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
  2205. &buffer_end, &buffer_size, *c))
  2206. {
  2207. failed = 1;
  2208. break;
  2209. }
  2210. }
  2211. else
  2212. {
  2213. /* This argument has been terminated by whitespace. */
  2214. if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
  2215. &pointer_end, &pointers_size,
  2216. local_buffer, &buffer_begin,
  2217. &buffer_end, &buffer_size))
  2218. {
  2219. failed = 1;
  2220. break;
  2221. }
  2222. in_argument = 0;
  2223. }
  2224. }
  2225. }
  2226. else
  2227. {
  2228. /* This character belong to an argument. */
  2229. if(!in_argument)
  2230. {
  2231. in_argument = 1;
  2232. }
  2233. if(!kwsysProcessAppendByte(local_buffer, &buffer_begin,
  2234. &buffer_end, &buffer_size, *c))
  2235. {
  2236. failed = 1;
  2237. break;
  2238. }
  2239. }
  2240. }
  2241. /* Finish the last argument. */
  2242. if(in_argument)
  2243. {
  2244. if(!kwsysProcessAppendArgument(local_pointers, &pointer_begin,
  2245. &pointer_end, &pointers_size,
  2246. local_buffer, &buffer_begin,
  2247. &buffer_end, &buffer_size))
  2248. {
  2249. failed = 1;
  2250. }
  2251. }
  2252. /* If we still have memory allocate space for the new command
  2253. buffer. */
  2254. if(!failed)
  2255. {
  2256. int n = pointer_end - pointer_begin;
  2257. newCommand = (char**)malloc((n+1)*sizeof(char*));
  2258. }
  2259. if(newCommand)
  2260. {
  2261. /* Copy the arguments into the new command buffer. */
  2262. int n = pointer_end - pointer_begin;
  2263. memcpy(newCommand, pointer_begin, sizeof(char*)*n);
  2264. newCommand[n] = 0;
  2265. }
  2266. else
  2267. {
  2268. /* Free arguments already allocated. */
  2269. while(pointer_end != pointer_begin)
  2270. {
  2271. free(*(--pointer_end));
  2272. }
  2273. }
  2274. /* Free temporary buffers. */
  2275. if(pointer_begin != local_pointers)
  2276. {
  2277. free(pointer_begin);
  2278. }
  2279. if(buffer_begin != local_buffer)
  2280. {
  2281. free(buffer_begin);
  2282. }
  2283. /* Return the final command buffer. */
  2284. return newCommand;
  2285. }