ProcessUNIX.c 85 KB

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