ProcessUNIX.c 75 KB

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