ProcessUNIX.c 85 KB

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