ProcessUNIX.c 79 KB

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