ProcessUNIX.c 84 KB

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