ProcessUNIX.c 86 KB

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