ProcessUNIX.c 84 KB

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