ProcessUNIX.c 81 KB

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