ProcessUNIX.c 78 KB

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