1
0

ProcessUNIX.c 84 KB

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