ProcessUNIX.c 75 KB

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