ProcessUNIX.c 78 KB

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