ProcessUNIX.c 76 KB

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