1
0

ProcessUNIX.c 86 KB

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