1
0

ProcessUNIX.c 85 KB

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