ProcessUNIX.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741
  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. /* Initialize the control structure for a new process. */
  629. if(!kwsysProcessInitialize(cp))
  630. {
  631. strcpy(cp->ErrorMessage, "Out of memory");
  632. cp->State = kwsysProcess_State_Error;
  633. return;
  634. }
  635. #if defined(__VMS)
  636. /* Make sure pipes behave like streams on VMS. */
  637. if(!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1))
  638. {
  639. kwsysProcessCleanup(cp, 1);
  640. return;
  641. }
  642. #endif
  643. /* Save the real working directory of this process and change to
  644. the working directory for the child processes. This is needed
  645. to make pipe file paths evaluate correctly. */
  646. if(cp->WorkingDirectory)
  647. {
  648. int r;
  649. if(!getcwd(cp->RealWorkingDirectory,
  650. (size_t)(cp->RealWorkingDirectoryLength)))
  651. {
  652. kwsysProcessCleanup(cp, 1);
  653. return;
  654. }
  655. /* Some platforms specify that the chdir call may be
  656. interrupted. Repeat the call until it finishes. */
  657. while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
  658. if(r < 0)
  659. {
  660. kwsysProcessCleanup(cp, 1);
  661. return;
  662. }
  663. }
  664. /* If not running a detached child, add this object to the global
  665. set of process objects that wish to be notified when a child
  666. exits. */
  667. if(!cp->OptionDetach)
  668. {
  669. if(!kwsysProcessesAdd(cp))
  670. {
  671. kwsysProcessCleanup(cp, 1);
  672. return;
  673. }
  674. }
  675. /* Setup the stderr pipe to be shared by all processes. */
  676. {
  677. /* Create the pipe. */
  678. int p[2];
  679. if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
  680. {
  681. kwsysProcessCleanup(cp, 1);
  682. return;
  683. }
  684. /* Store the pipe. */
  685. cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
  686. si.StdErr = p[1];
  687. /* Set close-on-exec flag on the pipe's ends. */
  688. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  689. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  690. {
  691. kwsysProcessCleanup(cp, 1);
  692. kwsysProcessCleanupDescriptor(&si.StdErr);
  693. return;
  694. }
  695. /* Set to non-blocking in case select lies, or for the polling
  696. implementation. */
  697. if(!kwsysProcessSetNonBlocking(p[0]))
  698. {
  699. kwsysProcessCleanup(cp, 1);
  700. kwsysProcessCleanupDescriptor(&si.StdErr);
  701. return;
  702. }
  703. }
  704. /* Replace the stderr pipe with a file if requested. In this case
  705. the select call will report that stderr is closed immediately. */
  706. if(cp->PipeFileSTDERR)
  707. {
  708. if(!kwsysProcessSetupOutputPipeFile(&si.StdErr, cp->PipeFileSTDERR))
  709. {
  710. kwsysProcessCleanup(cp, 1);
  711. kwsysProcessCleanupDescriptor(&si.StdErr);
  712. return;
  713. }
  714. }
  715. /* Replace the stderr pipe with the parent's if requested. In this
  716. case the select call will report that stderr is closed
  717. immediately. */
  718. if(cp->PipeSharedSTDERR)
  719. {
  720. kwsysProcessCleanupDescriptor(&si.StdErr);
  721. si.StdErr = 2;
  722. }
  723. /* Replace the stderr pipe with the native pipe provided if any. In
  724. this case the select call will report that stderr is closed
  725. immediately. */
  726. if(cp->PipeNativeSTDERR[1] >= 0)
  727. {
  728. if(!kwsysProcessSetupOutputPipeNative(&si.StdErr, cp->PipeNativeSTDERR))
  729. {
  730. kwsysProcessCleanup(cp, 1);
  731. kwsysProcessCleanupDescriptor(&si.StdErr);
  732. return;
  733. }
  734. }
  735. /* The timeout period starts now. */
  736. cp->StartTime = kwsysProcessTimeGetCurrent();
  737. cp->TimeoutTime.tv_sec = -1;
  738. cp->TimeoutTime.tv_usec = -1;
  739. /* Create the pipeline of processes. */
  740. {
  741. int readEnd = -1;
  742. int failed = 0;
  743. for(i=0; i < cp->NumberOfCommands; ++i)
  744. {
  745. if(!kwsysProcessCreate(cp, i, &si, &readEnd))
  746. {
  747. failed = 1;
  748. }
  749. /* Set the output pipe of the last process to be non-blocking in
  750. case select lies, or for the polling implementation. */
  751. if(i == (cp->NumberOfCommands-1) && !kwsysProcessSetNonBlocking(readEnd))
  752. {
  753. failed = 1;
  754. }
  755. if(failed)
  756. {
  757. kwsysProcessCleanup(cp, 1);
  758. /* Release resources that may have been allocated for this
  759. process before an error occurred. */
  760. kwsysProcessCleanupDescriptor(&readEnd);
  761. if(si.StdIn != 0)
  762. {
  763. kwsysProcessCleanupDescriptor(&si.StdIn);
  764. }
  765. if(si.StdOut != 1)
  766. {
  767. kwsysProcessCleanupDescriptor(&si.StdOut);
  768. }
  769. if(si.StdErr != 2)
  770. {
  771. kwsysProcessCleanupDescriptor(&si.StdErr);
  772. }
  773. kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
  774. kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
  775. return;
  776. }
  777. }
  778. /* Save a handle to the output pipe for the last process. */
  779. cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = readEnd;
  780. }
  781. /* The parent process does not need the output pipe write ends. */
  782. if(si.StdErr != 2)
  783. {
  784. kwsysProcessCleanupDescriptor(&si.StdErr);
  785. }
  786. /* Restore the working directory. */
  787. if(cp->RealWorkingDirectory)
  788. {
  789. /* Some platforms specify that the chdir call may be
  790. interrupted. Repeat the call until it finishes. */
  791. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  792. free(cp->RealWorkingDirectory);
  793. cp->RealWorkingDirectory = 0;
  794. }
  795. /* All the pipes are now open. */
  796. cp->PipesLeft = KWSYSPE_PIPE_COUNT;
  797. /* The process has now started. */
  798. cp->State = kwsysProcess_State_Executing;
  799. cp->Detached = cp->OptionDetach;
  800. }
  801. /*--------------------------------------------------------------------------*/
  802. kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
  803. {
  804. /* Make sure a detached child process is running. */
  805. if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
  806. cp->TimeoutExpired || cp->Killed)
  807. {
  808. return;
  809. }
  810. /* Close all the pipes safely. */
  811. kwsysProcessClosePipes(cp);
  812. /* We will not wait for exit, so cleanup now. */
  813. kwsysProcessCleanup(cp, 0);
  814. /* The process has been disowned. */
  815. cp->State = kwsysProcess_State_Disowned;
  816. }
  817. /*--------------------------------------------------------------------------*/
  818. typedef struct kwsysProcessWaitData_s
  819. {
  820. int Expired;
  821. int PipeId;
  822. int User;
  823. double* UserTimeout;
  824. kwsysProcessTime TimeoutTime;
  825. } kwsysProcessWaitData;
  826. static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
  827. kwsysProcessWaitData* wd);
  828. /*--------------------------------------------------------------------------*/
  829. int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
  830. double* userTimeout)
  831. {
  832. kwsysProcessTime userStartTime = {0, 0};
  833. kwsysProcessWaitData wd =
  834. {
  835. 0,
  836. kwsysProcess_Pipe_None,
  837. 0,
  838. 0,
  839. {0, 0}
  840. };
  841. wd.UserTimeout = userTimeout;
  842. /* Make sure we are executing a process. */
  843. if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
  844. cp->TimeoutExpired)
  845. {
  846. return kwsysProcess_Pipe_None;
  847. }
  848. /* Record the time at which user timeout period starts. */
  849. if(userTimeout)
  850. {
  851. userStartTime = kwsysProcessTimeGetCurrent();
  852. }
  853. /* Calculate the time at which a timeout will expire, and whether it
  854. is the user or process timeout. */
  855. wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
  856. &wd.TimeoutTime);
  857. /* Data can only be available when pipes are open. If the process
  858. is not running, cp->PipesLeft will be 0. */
  859. while(cp->PipesLeft > 0 &&
  860. !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
  861. /* Update the user timeout. */
  862. if(userTimeout)
  863. {
  864. kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
  865. kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
  866. userStartTime);
  867. double d = kwsysProcessTimeToDouble(difference);
  868. *userTimeout -= d;
  869. if(*userTimeout < 0)
  870. {
  871. *userTimeout = 0;
  872. }
  873. }
  874. /* Check what happened. */
  875. if(wd.PipeId)
  876. {
  877. /* Data are ready on a pipe. */
  878. return wd.PipeId;
  879. }
  880. else if(wd.Expired)
  881. {
  882. /* A timeout has expired. */
  883. if(wd.User)
  884. {
  885. /* The user timeout has expired. It has no time left. */
  886. return kwsysProcess_Pipe_Timeout;
  887. }
  888. else
  889. {
  890. /* The process timeout has expired. Kill the children now. */
  891. kwsysProcess_Kill(cp);
  892. cp->Killed = 0;
  893. cp->TimeoutExpired = 1;
  894. return kwsysProcess_Pipe_None;
  895. }
  896. }
  897. else
  898. {
  899. /* No pipes are left open. */
  900. return kwsysProcess_Pipe_None;
  901. }
  902. }
  903. /*--------------------------------------------------------------------------*/
  904. static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
  905. kwsysProcessWaitData* wd)
  906. {
  907. int i;
  908. kwsysProcessTimeNative timeoutLength;
  909. #if KWSYSPE_USE_SELECT
  910. int numReady = 0;
  911. int max = -1;
  912. kwsysProcessTimeNative* timeout = 0;
  913. /* Check for any open pipes with data reported ready by the last
  914. call to select. According to "man select_tut" we must deal
  915. with all descriptors reported by a call to select before
  916. passing them to another select call. */
  917. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  918. {
  919. if(cp->PipeReadEnds[i] >= 0 &&
  920. FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  921. {
  922. kwsysProcess_ssize_t n;
  923. /* We are handling this pipe now. Remove it from the set. */
  924. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  925. /* The pipe is ready to read without blocking. Keep trying to
  926. read until the operation is not interrupted. */
  927. while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
  928. KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
  929. if(n > 0)
  930. {
  931. /* We have data on this pipe. */
  932. if(i == KWSYSPE_PIPE_SIGNAL)
  933. {
  934. /* A child process has terminated. */
  935. kwsysProcessDestroy(cp);
  936. }
  937. else if(data && length)
  938. {
  939. /* Report this data. */
  940. *data = cp->PipeBuffer;
  941. *length = (int)(n);
  942. switch(i)
  943. {
  944. case KWSYSPE_PIPE_STDOUT:
  945. wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
  946. case KWSYSPE_PIPE_STDERR:
  947. wd->PipeId = kwsysProcess_Pipe_STDERR; break;
  948. };
  949. return 1;
  950. }
  951. }
  952. else if(n < 0 && errno == EAGAIN)
  953. {
  954. /* No data are really ready. The select call lied. See the
  955. "man select" page on Linux for cases when this occurs. */
  956. }
  957. else
  958. {
  959. /* We are done reading from this pipe. */
  960. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  961. --cp->PipesLeft;
  962. }
  963. }
  964. }
  965. /* If we have data, break early. */
  966. if(wd->PipeId)
  967. {
  968. return 1;
  969. }
  970. /* Make sure the set is empty (it should always be empty here
  971. anyway). */
  972. FD_ZERO(&cp->PipeSet);
  973. /* Setup a timeout if required. */
  974. if(wd->TimeoutTime.tv_sec < 0)
  975. {
  976. timeout = 0;
  977. }
  978. else
  979. {
  980. timeout = &timeoutLength;
  981. }
  982. if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
  983. wd->User?wd->UserTimeout:0,
  984. &timeoutLength, 0))
  985. {
  986. /* Timeout has already expired. */
  987. wd->Expired = 1;
  988. return 1;
  989. }
  990. /* Add the pipe reading ends that are still open. */
  991. max = -1;
  992. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  993. {
  994. if(cp->PipeReadEnds[i] >= 0)
  995. {
  996. FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
  997. if(cp->PipeReadEnds[i] > max)
  998. {
  999. max = cp->PipeReadEnds[i];
  1000. }
  1001. }
  1002. }
  1003. /* Make sure we have a non-empty set. */
  1004. if(max < 0)
  1005. {
  1006. /* All pipes have closed. Child has terminated. */
  1007. return 1;
  1008. }
  1009. /* Run select to block until data are available. Repeat call
  1010. until it is not interrupted. */
  1011. while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
  1012. (errno == EINTR));
  1013. /* Check result of select. */
  1014. if(numReady == 0)
  1015. {
  1016. /* Select's timeout expired. */
  1017. wd->Expired = 1;
  1018. return 1;
  1019. }
  1020. else if(numReady < 0)
  1021. {
  1022. /* Select returned an error. Leave the error description in the
  1023. pipe buffer. */
  1024. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1025. /* Kill the children now. */
  1026. kwsysProcess_Kill(cp);
  1027. cp->Killed = 0;
  1028. cp->SelectError = 1;
  1029. }
  1030. return 0;
  1031. #else
  1032. /* Poll pipes for data since we do not have select. */
  1033. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  1034. {
  1035. if(cp->PipeReadEnds[i] >= 0)
  1036. {
  1037. const int fd = cp->PipeReadEnds[i];
  1038. int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
  1039. if(n > 0)
  1040. {
  1041. /* We have data on this pipe. */
  1042. if(i == KWSYSPE_PIPE_SIGNAL)
  1043. {
  1044. /* A child process has terminated. */
  1045. kwsysProcessDestroy(cp);
  1046. }
  1047. else if(data && length)
  1048. {
  1049. /* Report this data. */
  1050. *data = cp->PipeBuffer;
  1051. *length = n;
  1052. switch(i)
  1053. {
  1054. case KWSYSPE_PIPE_STDOUT:
  1055. wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
  1056. case KWSYSPE_PIPE_STDERR:
  1057. wd->PipeId = kwsysProcess_Pipe_STDERR; break;
  1058. };
  1059. }
  1060. return 1;
  1061. }
  1062. else if (n == 0) /* EOF */
  1063. {
  1064. /* We are done reading from this pipe. */
  1065. #if defined(__VMS)
  1066. if(!cp->CommandsLeft)
  1067. #endif
  1068. {
  1069. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  1070. --cp->PipesLeft;
  1071. }
  1072. }
  1073. else if (n < 0) /* error */
  1074. {
  1075. #if defined(__VMS)
  1076. if(!cp->CommandsLeft)
  1077. {
  1078. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  1079. --cp->PipesLeft;
  1080. }
  1081. else
  1082. #endif
  1083. if((errno != EINTR) && (errno != EAGAIN))
  1084. {
  1085. strncpy(cp->ErrorMessage,strerror(errno),
  1086. KWSYSPE_PIPE_BUFFER_SIZE);
  1087. /* Kill the children now. */
  1088. kwsysProcess_Kill(cp);
  1089. cp->Killed = 0;
  1090. cp->SelectError = 1;
  1091. return 1;
  1092. }
  1093. }
  1094. }
  1095. }
  1096. /* If we have data, break early. */
  1097. if(wd->PipeId)
  1098. {
  1099. return 1;
  1100. }
  1101. if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
  1102. &timeoutLength, 1))
  1103. {
  1104. /* Timeout has already expired. */
  1105. wd->Expired = 1;
  1106. return 1;
  1107. }
  1108. /* Sleep a little, try again. */
  1109. {
  1110. unsigned int msec = ((timeoutLength.tv_sec * 1000) +
  1111. (timeoutLength.tv_usec / 1000));
  1112. if (msec > 100000)
  1113. {
  1114. msec = 100000; /* do not sleep more than 100 milliseconds at a time */
  1115. }
  1116. kwsysProcess_usleep(msec);
  1117. }
  1118. return 0;
  1119. #endif
  1120. }
  1121. /*--------------------------------------------------------------------------*/
  1122. int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
  1123. {
  1124. int status = 0;
  1125. int prPipe = 0;
  1126. /* Make sure we are executing a process. */
  1127. if(!cp || cp->State != kwsysProcess_State_Executing)
  1128. {
  1129. return 1;
  1130. }
  1131. /* Wait for all the pipes to close. Ignore all data. */
  1132. while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
  1133. {
  1134. if(prPipe == kwsysProcess_Pipe_Timeout)
  1135. {
  1136. return 0;
  1137. }
  1138. }
  1139. /* Check if there was an error in one of the waitpid calls. */
  1140. if(cp->State == kwsysProcess_State_Error)
  1141. {
  1142. /* The error message is already in its buffer. Tell
  1143. kwsysProcessCleanup to not create it. */
  1144. kwsysProcessCleanup(cp, 0);
  1145. return 1;
  1146. }
  1147. /* Check whether the child reported an error invoking the process. */
  1148. if(cp->SelectError)
  1149. {
  1150. /* The error message is already in its buffer. Tell
  1151. kwsysProcessCleanup to not create it. */
  1152. kwsysProcessCleanup(cp, 0);
  1153. cp->State = kwsysProcess_State_Error;
  1154. return 1;
  1155. }
  1156. /* Use the status of the last process in the pipeline. */
  1157. status = cp->CommandExitCodes[cp->NumberOfCommands-1];
  1158. /* Determine the outcome. */
  1159. if(cp->Killed)
  1160. {
  1161. /* We killed the child. */
  1162. cp->State = kwsysProcess_State_Killed;
  1163. }
  1164. else if(cp->TimeoutExpired)
  1165. {
  1166. /* The timeout expired. */
  1167. cp->State = kwsysProcess_State_Expired;
  1168. }
  1169. else if(WIFEXITED(status))
  1170. {
  1171. /* The child exited normally. */
  1172. cp->State = kwsysProcess_State_Exited;
  1173. cp->ExitException = kwsysProcess_Exception_None;
  1174. cp->ExitCode = status;
  1175. cp->ExitValue = (int)WEXITSTATUS(status);
  1176. }
  1177. else if(WIFSIGNALED(status))
  1178. {
  1179. /* The child received an unhandled signal. */
  1180. cp->State = kwsysProcess_State_Exception;
  1181. cp->ExitCode = status;
  1182. kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
  1183. }
  1184. else
  1185. {
  1186. /* Error getting the child return code. */
  1187. strcpy(cp->ErrorMessage, "Error getting child return code.");
  1188. cp->State = kwsysProcess_State_Error;
  1189. }
  1190. /* Normal cleanup. */
  1191. kwsysProcessCleanup(cp, 0);
  1192. return 1;
  1193. }
  1194. /*--------------------------------------------------------------------------*/
  1195. void kwsysProcess_Kill(kwsysProcess* cp)
  1196. {
  1197. int i;
  1198. /* Make sure we are executing a process. */
  1199. if(!cp || cp->State != kwsysProcess_State_Executing)
  1200. {
  1201. return;
  1202. }
  1203. /* First close the child exit report pipe write end to avoid causing a
  1204. SIGPIPE when the child terminates and our signal handler tries to
  1205. report it after we have already closed the read end. */
  1206. kwsysProcessCleanupDescriptor(&cp->SignalPipe);
  1207. #if !defined(__APPLE__)
  1208. /* Close all the pipe read ends. Do this before killing the
  1209. children because Cygwin has problems killing processes that are
  1210. blocking to wait for writing to their output pipes. */
  1211. kwsysProcessClosePipes(cp);
  1212. #endif
  1213. /* Kill the children. */
  1214. cp->Killed = 1;
  1215. for(i=0; i < cp->NumberOfCommands; ++i)
  1216. {
  1217. int status;
  1218. if(cp->ForkPIDs[i])
  1219. {
  1220. /* Kill the child. */
  1221. kwsysProcessKill(cp->ForkPIDs[i]);
  1222. /* Reap the child. Keep trying until the call is not
  1223. interrupted. */
  1224. while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
  1225. }
  1226. }
  1227. #if defined(__APPLE__)
  1228. /* Close all the pipe read ends. Do this after killing the
  1229. children because OS X has problems closing pipe read ends whose
  1230. pipes are full and still have an open write end. */
  1231. kwsysProcessClosePipes(cp);
  1232. #endif
  1233. cp->CommandsLeft = 0;
  1234. }
  1235. /*--------------------------------------------------------------------------*/
  1236. /* Initialize a process control structure for kwsysProcess_Execute. */
  1237. static int kwsysProcessInitialize(kwsysProcess* cp)
  1238. {
  1239. int i;
  1240. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  1241. {
  1242. cp->PipeReadEnds[i] = -1;
  1243. }
  1244. cp->SignalPipe = -1;
  1245. cp->SelectError = 0;
  1246. cp->StartTime.tv_sec = -1;
  1247. cp->StartTime.tv_usec = -1;
  1248. cp->TimeoutTime.tv_sec = -1;
  1249. cp->TimeoutTime.tv_usec = -1;
  1250. cp->TimeoutExpired = 0;
  1251. cp->PipesLeft = 0;
  1252. cp->CommandsLeft = 0;
  1253. #if KWSYSPE_USE_SELECT
  1254. FD_ZERO(&cp->PipeSet);
  1255. #endif
  1256. cp->State = kwsysProcess_State_Starting;
  1257. cp->Killed = 0;
  1258. cp->ExitException = kwsysProcess_Exception_None;
  1259. cp->ExitCode = 1;
  1260. cp->ExitValue = 1;
  1261. cp->ErrorMessage[0] = 0;
  1262. strcpy(cp->ExitExceptionString, "No exception");
  1263. if(cp->ForkPIDs)
  1264. {
  1265. free(cp->ForkPIDs);
  1266. }
  1267. cp->ForkPIDs = (pid_t*)malloc(sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
  1268. if(!cp->ForkPIDs)
  1269. {
  1270. return 0;
  1271. }
  1272. memset(cp->ForkPIDs, 0, sizeof(pid_t)*(size_t)(cp->NumberOfCommands));
  1273. if(cp->CommandExitCodes)
  1274. {
  1275. free(cp->CommandExitCodes);
  1276. }
  1277. cp->CommandExitCodes = (int*)malloc(sizeof(int)*
  1278. (size_t)(cp->NumberOfCommands));
  1279. if(!cp->CommandExitCodes)
  1280. {
  1281. return 0;
  1282. }
  1283. memset(cp->CommandExitCodes, 0, sizeof(int)*(size_t)(cp->NumberOfCommands));
  1284. /* Allocate memory to save the real working directory. */
  1285. if ( cp->WorkingDirectory )
  1286. {
  1287. #if defined(MAXPATHLEN)
  1288. cp->RealWorkingDirectoryLength = MAXPATHLEN;
  1289. #elif defined(PATH_MAX)
  1290. cp->RealWorkingDirectoryLength = PATH_MAX;
  1291. #else
  1292. cp->RealWorkingDirectoryLength = 4096;
  1293. #endif
  1294. cp->RealWorkingDirectory =
  1295. malloc((size_t)(cp->RealWorkingDirectoryLength));
  1296. if(!cp->RealWorkingDirectory)
  1297. {
  1298. return 0;
  1299. }
  1300. }
  1301. return 1;
  1302. }
  1303. /*--------------------------------------------------------------------------*/
  1304. /* Free all resources used by the given kwsysProcess instance that were
  1305. allocated by kwsysProcess_Execute. */
  1306. static void kwsysProcessCleanup(kwsysProcess* cp, int error)
  1307. {
  1308. int i;
  1309. if(error)
  1310. {
  1311. /* We are cleaning up due to an error. Report the error message
  1312. if one has not been provided already. */
  1313. if(cp->ErrorMessage[0] == 0)
  1314. {
  1315. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1316. }
  1317. /* Set the error state. */
  1318. cp->State = kwsysProcess_State_Error;
  1319. /* Kill any children already started. */
  1320. if(cp->ForkPIDs)
  1321. {
  1322. int status;
  1323. for(i=0; i < cp->NumberOfCommands; ++i)
  1324. {
  1325. if(cp->ForkPIDs[i])
  1326. {
  1327. /* Kill the child. */
  1328. kwsysProcessKill(cp->ForkPIDs[i]);
  1329. /* Reap the child. Keep trying until the call is not
  1330. interrupted. */
  1331. while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
  1332. (errno == EINTR));
  1333. }
  1334. }
  1335. }
  1336. /* Restore the working directory. */
  1337. if(cp->RealWorkingDirectory)
  1338. {
  1339. while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
  1340. }
  1341. }
  1342. /* If not creating a detached child, remove this object from the
  1343. global set of process objects that wish to be notified when a
  1344. child exits. */
  1345. if(!cp->OptionDetach)
  1346. {
  1347. kwsysProcessesRemove(cp);
  1348. }
  1349. /* Free memory. */
  1350. if(cp->ForkPIDs)
  1351. {
  1352. free(cp->ForkPIDs);
  1353. cp->ForkPIDs = 0;
  1354. }
  1355. if(cp->RealWorkingDirectory)
  1356. {
  1357. free(cp->RealWorkingDirectory);
  1358. cp->RealWorkingDirectory = 0;
  1359. }
  1360. /* Close pipe handles. */
  1361. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  1362. {
  1363. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  1364. }
  1365. }
  1366. /*--------------------------------------------------------------------------*/
  1367. /* Close the given file descriptor if it is open. Reset its value to -1. */
  1368. static void kwsysProcessCleanupDescriptor(int* pfd)
  1369. {
  1370. if(pfd && *pfd >= 0)
  1371. {
  1372. /* Keep trying to close until it is not interrupted by a
  1373. * signal. */
  1374. while((close(*pfd) < 0) && (errno == EINTR));
  1375. *pfd = -1;
  1376. }
  1377. }
  1378. /*--------------------------------------------------------------------------*/
  1379. static void kwsysProcessClosePipes(kwsysProcess* cp)
  1380. {
  1381. int i;
  1382. /* Close any pipes that are still open. */
  1383. for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
  1384. {
  1385. if(cp->PipeReadEnds[i] >= 0)
  1386. {
  1387. #if KWSYSPE_USE_SELECT
  1388. /* If the pipe was reported by the last call to select, we must
  1389. read from it. This is needed to satisfy the suggestions from
  1390. "man select_tut" and is not needed for the polling
  1391. implementation. Ignore the data. */
  1392. if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
  1393. {
  1394. /* We are handling this pipe now. Remove it from the set. */
  1395. FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
  1396. /* The pipe is ready to read without blocking. Keep trying to
  1397. read until the operation is not interrupted. */
  1398. while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
  1399. KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
  1400. }
  1401. #endif
  1402. /* We are done reading from this pipe. */
  1403. kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
  1404. --cp->PipesLeft;
  1405. }
  1406. }
  1407. }
  1408. /*--------------------------------------------------------------------------*/
  1409. static int kwsysProcessSetNonBlocking(int fd)
  1410. {
  1411. int flags = fcntl(fd, F_GETFL);
  1412. if(flags >= 0)
  1413. {
  1414. flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  1415. }
  1416. return flags >= 0;
  1417. }
  1418. /*--------------------------------------------------------------------------*/
  1419. #if defined(__VMS)
  1420. int decc$set_child_standard_streams(int fd1, int fd2, int fd3);
  1421. #endif
  1422. /*--------------------------------------------------------------------------*/
  1423. static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
  1424. kwsysProcessCreateInformation* si, int* readEnd)
  1425. {
  1426. /* Setup the process's stdin. */
  1427. if(prIndex > 0)
  1428. {
  1429. si->StdIn = *readEnd;
  1430. *readEnd = 0;
  1431. }
  1432. else if(cp->PipeFileSTDIN)
  1433. {
  1434. /* Open a file for the child's stdin to read. */
  1435. si->StdIn = open(cp->PipeFileSTDIN, O_RDONLY);
  1436. if(si->StdIn < 0)
  1437. {
  1438. return 0;
  1439. }
  1440. /* Set close-on-exec flag on the pipe's end. */
  1441. if(fcntl(si->StdIn, F_SETFD, FD_CLOEXEC) < 0)
  1442. {
  1443. return 0;
  1444. }
  1445. }
  1446. else if(cp->PipeSharedSTDIN)
  1447. {
  1448. si->StdIn = 0;
  1449. }
  1450. else if(cp->PipeNativeSTDIN[0] >= 0)
  1451. {
  1452. si->StdIn = cp->PipeNativeSTDIN[0];
  1453. /* Set close-on-exec flag on the pipe's ends. The read end will
  1454. be dup2-ed into the stdin descriptor after the fork but before
  1455. the exec. */
  1456. if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
  1457. (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
  1458. {
  1459. return 0;
  1460. }
  1461. }
  1462. else
  1463. {
  1464. si->StdIn = -1;
  1465. }
  1466. /* Setup the process's stdout. */
  1467. {
  1468. /* Create the pipe. */
  1469. int p[2];
  1470. if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
  1471. {
  1472. return 0;
  1473. }
  1474. *readEnd = p[0];
  1475. si->StdOut = p[1];
  1476. /* Set close-on-exec flag on the pipe's ends. */
  1477. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  1478. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  1479. {
  1480. return 0;
  1481. }
  1482. }
  1483. /* Replace the stdout pipe with a file if requested. In this case
  1484. the select call will report that stdout is closed immediately. */
  1485. if(prIndex == cp->NumberOfCommands-1 && cp->PipeFileSTDOUT)
  1486. {
  1487. if(!kwsysProcessSetupOutputPipeFile(&si->StdOut, cp->PipeFileSTDOUT))
  1488. {
  1489. return 0;
  1490. }
  1491. }
  1492. /* Replace the stdout pipe with the parent's if requested. In this
  1493. case the select call will report that stderr is closed
  1494. immediately. */
  1495. if(prIndex == cp->NumberOfCommands-1 && cp->PipeSharedSTDOUT)
  1496. {
  1497. kwsysProcessCleanupDescriptor(&si->StdOut);
  1498. si->StdOut = 1;
  1499. }
  1500. /* Replace the stdout pipe with the native pipe provided if any. In
  1501. this case the select call will report that stdout is closed
  1502. immediately. */
  1503. if(prIndex == cp->NumberOfCommands-1 && cp->PipeNativeSTDOUT[1] >= 0)
  1504. {
  1505. if(!kwsysProcessSetupOutputPipeNative(&si->StdOut, cp->PipeNativeSTDOUT))
  1506. {
  1507. return 0;
  1508. }
  1509. }
  1510. /* Create the error reporting pipe. */
  1511. if(pipe(si->ErrorPipe) < 0)
  1512. {
  1513. return 0;
  1514. }
  1515. /* Set close-on-exec flag on the error pipe's write end. */
  1516. if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0)
  1517. {
  1518. return 0;
  1519. }
  1520. /* Fork off a child process. */
  1521. #if defined(__VMS)
  1522. /* VMS needs vfork and execvp to be in the same function because
  1523. they use setjmp/longjmp to run the child startup code in the
  1524. parent! TODO: OptionDetach. */
  1525. cp->ForkPIDs[prIndex] = vfork();
  1526. #else
  1527. cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
  1528. #endif
  1529. if(cp->ForkPIDs[prIndex] < 0)
  1530. {
  1531. return 0;
  1532. }
  1533. if(cp->ForkPIDs[prIndex] == 0)
  1534. {
  1535. #if defined(__VMS)
  1536. /* Specify standard pipes for child process. */
  1537. decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr);
  1538. #else
  1539. /* Close the read end of the error reporting pipe. */
  1540. close(si->ErrorPipe[0]);
  1541. /* Setup the stdin, stdout, and stderr pipes. */
  1542. if(si->StdIn > 0)
  1543. {
  1544. dup2(si->StdIn, 0);
  1545. }
  1546. else if(si->StdIn < 0)
  1547. {
  1548. close(0);
  1549. }
  1550. if(si->StdOut != 1)
  1551. {
  1552. dup2(si->StdOut, 1);
  1553. }
  1554. if(si->StdErr != 2)
  1555. {
  1556. dup2(si->StdErr, 2);
  1557. }
  1558. /* Clear the close-on-exec flag for stdin, stdout, and stderr.
  1559. All other pipe handles will be closed when exec succeeds. */
  1560. fcntl(0, F_SETFD, 0);
  1561. fcntl(1, F_SETFD, 0);
  1562. fcntl(2, F_SETFD, 0);
  1563. /* Restore all default signal handlers. */
  1564. kwsysProcessRestoreDefaultSignalHandlers();
  1565. #endif
  1566. /* Execute the real process. If successful, this does not return. */
  1567. execvp(cp->Commands[prIndex][0], cp->Commands[prIndex]);
  1568. /* TODO: What does VMS do if the child fails to start? */
  1569. /* Failure. Report error to parent and terminate. */
  1570. kwsysProcessChildErrorExit(si->ErrorPipe[1]);
  1571. }
  1572. #if defined(__VMS)
  1573. /* Restore the standard pipes of this process. */
  1574. decc$set_child_standard_streams(0, 1, 2);
  1575. #endif
  1576. /* A child has been created. */
  1577. ++cp->CommandsLeft;
  1578. /* We are done with the error reporting pipe write end. */
  1579. kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
  1580. /* Block until the child's exec call succeeds and closes the error
  1581. pipe or writes data to the pipe to report an error. */
  1582. {
  1583. kwsysProcess_ssize_t total = 0;
  1584. kwsysProcess_ssize_t n = 1;
  1585. /* Read the entire error message up to the length of our buffer. */
  1586. while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
  1587. {
  1588. /* Keep trying to read until the operation is not interrupted. */
  1589. while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
  1590. (size_t)(KWSYSPE_PIPE_BUFFER_SIZE-total))) < 0) &&
  1591. (errno == EINTR));
  1592. if(n > 0)
  1593. {
  1594. total += n;
  1595. }
  1596. }
  1597. /* We are done with the error reporting pipe read end. */
  1598. kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
  1599. if(total > 0)
  1600. {
  1601. /* The child failed to execute the process. */
  1602. return 0;
  1603. }
  1604. }
  1605. /* Successfully created this child process. */
  1606. if(prIndex > 0 || si->StdIn > 0)
  1607. {
  1608. /* The parent process does not need the input pipe read end. */
  1609. kwsysProcessCleanupDescriptor(&si->StdIn);
  1610. }
  1611. /* The parent process does not need the output pipe write ends. */
  1612. if(si->StdOut != 1)
  1613. {
  1614. kwsysProcessCleanupDescriptor(&si->StdOut);
  1615. }
  1616. return 1;
  1617. }
  1618. /*--------------------------------------------------------------------------*/
  1619. static void kwsysProcessDestroy(kwsysProcess* cp)
  1620. {
  1621. /* A child process has terminated. Reap it if it is one handled by
  1622. this object. */
  1623. int i;
  1624. for(i=0; i < cp->NumberOfCommands; ++i)
  1625. {
  1626. if(cp->ForkPIDs[i])
  1627. {
  1628. int result;
  1629. while(((result = waitpid(cp->ForkPIDs[i],
  1630. &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
  1631. (errno == EINTR));
  1632. if(result > 0)
  1633. {
  1634. /* This child has termianted. */
  1635. cp->ForkPIDs[i] = 0;
  1636. if(--cp->CommandsLeft == 0)
  1637. {
  1638. /* All children have terminated. Close the signal pipe
  1639. write end so that no more notifications are sent to this
  1640. object. */
  1641. kwsysProcessCleanupDescriptor(&cp->SignalPipe);
  1642. /* TODO: Once the children have terminated, switch
  1643. WaitForData to use a non-blocking read to get the
  1644. rest of the data from the pipe. This is needed when
  1645. grandchildren keep the output pipes open. */
  1646. }
  1647. }
  1648. else if(result < 0 && cp->State != kwsysProcess_State_Error)
  1649. {
  1650. /* Unexpected error. Report the first time this happens. */
  1651. strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1652. cp->State = kwsysProcess_State_Error;
  1653. }
  1654. }
  1655. }
  1656. }
  1657. /*--------------------------------------------------------------------------*/
  1658. static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
  1659. {
  1660. int fout;
  1661. if(!name)
  1662. {
  1663. return 1;
  1664. }
  1665. /* Close the existing descriptor. */
  1666. kwsysProcessCleanupDescriptor(p);
  1667. /* Open a file for the pipe to write. */
  1668. if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
  1669. {
  1670. return 0;
  1671. }
  1672. /* Set close-on-exec flag on the pipe's end. */
  1673. if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
  1674. {
  1675. return 0;
  1676. }
  1677. /* Assign the replacement descriptor. */
  1678. *p = fout;
  1679. return 1;
  1680. }
  1681. /*--------------------------------------------------------------------------*/
  1682. static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
  1683. {
  1684. /* Close the existing descriptor. */
  1685. kwsysProcessCleanupDescriptor(p);
  1686. /* Set close-on-exec flag on the pipe's ends. The proper end will
  1687. be dup2-ed into the standard descriptor number after fork but
  1688. before exec. */
  1689. if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
  1690. (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
  1691. {
  1692. return 0;
  1693. }
  1694. /* Assign the replacement descriptor. */
  1695. *p = des[1];
  1696. return 1;
  1697. }
  1698. /*--------------------------------------------------------------------------*/
  1699. /* Get the time at which either the process or user timeout will
  1700. expire. Returns 1 if the user timeout is first, and 0 otherwise. */
  1701. static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
  1702. kwsysProcessTime* timeoutTime)
  1703. {
  1704. /* The first time this is called, we need to calculate the time at
  1705. which the child will timeout. */
  1706. if(cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0)
  1707. {
  1708. kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
  1709. cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
  1710. }
  1711. /* Start with process timeout. */
  1712. *timeoutTime = cp->TimeoutTime;
  1713. /* Check if the user timeout is earlier. */
  1714. if(userTimeout)
  1715. {
  1716. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1717. kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
  1718. kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
  1719. userTimeoutLength);
  1720. if(timeoutTime->tv_sec < 0 ||
  1721. kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
  1722. {
  1723. *timeoutTime = userTimeoutTime;
  1724. return 1;
  1725. }
  1726. }
  1727. return 0;
  1728. }
  1729. /*--------------------------------------------------------------------------*/
  1730. /* Get the length of time before the given timeout time arrives.
  1731. Returns 1 if the time has already arrived, and 0 otherwise. */
  1732. static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
  1733. double* userTimeout,
  1734. kwsysProcessTimeNative* timeoutLength,
  1735. int zeroIsExpired)
  1736. {
  1737. if(timeoutTime->tv_sec < 0)
  1738. {
  1739. /* No timeout time has been requested. */
  1740. return 0;
  1741. }
  1742. else
  1743. {
  1744. /* Calculate the remaining time. */
  1745. kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
  1746. kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
  1747. currentTime);
  1748. if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
  1749. {
  1750. /* Caller has explicitly requested a zero timeout. */
  1751. timeLeft.tv_sec = 0;
  1752. timeLeft.tv_usec = 0;
  1753. }
  1754. if(timeLeft.tv_sec < 0 ||
  1755. (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired))
  1756. {
  1757. /* Timeout has already expired. */
  1758. return 1;
  1759. }
  1760. else
  1761. {
  1762. /* There is some time left. */
  1763. timeoutLength->tv_sec = timeLeft.tv_sec;
  1764. timeoutLength->tv_usec = timeLeft.tv_usec;
  1765. return 0;
  1766. }
  1767. }
  1768. }
  1769. /*--------------------------------------------------------------------------*/
  1770. static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
  1771. {
  1772. kwsysProcessTime current;
  1773. kwsysProcessTimeNative current_native;
  1774. gettimeofday(&current_native, 0);
  1775. current.tv_sec = (long)current_native.tv_sec;
  1776. current.tv_usec = (long)current_native.tv_usec;
  1777. return current;
  1778. }
  1779. /*--------------------------------------------------------------------------*/
  1780. static double kwsysProcessTimeToDouble(kwsysProcessTime t)
  1781. {
  1782. return (double)t.tv_sec + (double)(t.tv_usec)*0.000001;
  1783. }
  1784. /*--------------------------------------------------------------------------*/
  1785. static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
  1786. {
  1787. kwsysProcessTime t;
  1788. t.tv_sec = (long)d;
  1789. t.tv_usec = (long)((d-(double)(t.tv_sec))*1000000);
  1790. return t;
  1791. }
  1792. /*--------------------------------------------------------------------------*/
  1793. static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
  1794. {
  1795. return ((in1.tv_sec < in2.tv_sec) ||
  1796. ((in1.tv_sec == in2.tv_sec) && (in1.tv_usec < in2.tv_usec)));
  1797. }
  1798. /*--------------------------------------------------------------------------*/
  1799. static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
  1800. {
  1801. kwsysProcessTime out;
  1802. out.tv_sec = in1.tv_sec + in2.tv_sec;
  1803. out.tv_usec = in1.tv_usec + in2.tv_usec;
  1804. if(out.tv_usec > 1000000)
  1805. {
  1806. out.tv_usec -= 1000000;
  1807. out.tv_sec += 1;
  1808. }
  1809. return out;
  1810. }
  1811. /*--------------------------------------------------------------------------*/
  1812. static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
  1813. {
  1814. kwsysProcessTime out;
  1815. out.tv_sec = in1.tv_sec - in2.tv_sec;
  1816. out.tv_usec = in1.tv_usec - in2.tv_usec;
  1817. if(out.tv_usec < 0)
  1818. {
  1819. out.tv_usec += 1000000;
  1820. out.tv_sec -= 1;
  1821. }
  1822. return out;
  1823. }
  1824. /*--------------------------------------------------------------------------*/
  1825. #define KWSYSPE_CASE(type, str) \
  1826. cp->ExitException = kwsysProcess_Exception_##type; \
  1827. strcpy(cp->ExitExceptionString, str)
  1828. static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
  1829. {
  1830. switch (sig)
  1831. {
  1832. #ifdef SIGSEGV
  1833. case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
  1834. #endif
  1835. #ifdef SIGBUS
  1836. # if !defined(SIGSEGV) || SIGBUS != SIGSEGV
  1837. case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
  1838. # endif
  1839. #endif
  1840. #ifdef SIGFPE
  1841. case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
  1842. #endif
  1843. #ifdef SIGILL
  1844. case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
  1845. #endif
  1846. #ifdef SIGINT
  1847. case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
  1848. #endif
  1849. #ifdef SIGABRT
  1850. case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
  1851. #endif
  1852. #ifdef SIGKILL
  1853. case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
  1854. #endif
  1855. #ifdef SIGTERM
  1856. case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
  1857. #endif
  1858. #ifdef SIGHUP
  1859. case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
  1860. #endif
  1861. #ifdef SIGQUIT
  1862. case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
  1863. #endif
  1864. #ifdef SIGTRAP
  1865. case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
  1866. #endif
  1867. #ifdef SIGIOT
  1868. # if !defined(SIGABRT) || SIGIOT != SIGABRT
  1869. case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
  1870. # endif
  1871. #endif
  1872. #ifdef SIGUSR1
  1873. case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
  1874. #endif
  1875. #ifdef SIGUSR2
  1876. case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
  1877. #endif
  1878. #ifdef SIGPIPE
  1879. case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
  1880. #endif
  1881. #ifdef SIGALRM
  1882. case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
  1883. #endif
  1884. #ifdef SIGSTKFLT
  1885. case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
  1886. #endif
  1887. #ifdef SIGCHLD
  1888. case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
  1889. #elif defined(SIGCLD)
  1890. case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
  1891. #endif
  1892. #ifdef SIGCONT
  1893. case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
  1894. #endif
  1895. #ifdef SIGSTOP
  1896. case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
  1897. #endif
  1898. #ifdef SIGTSTP
  1899. case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
  1900. #endif
  1901. #ifdef SIGTTIN
  1902. case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
  1903. #endif
  1904. #ifdef SIGTTOU
  1905. case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
  1906. #endif
  1907. #ifdef SIGURG
  1908. case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
  1909. #endif
  1910. #ifdef SIGXCPU
  1911. case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
  1912. #endif
  1913. #ifdef SIGXFSZ
  1914. case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
  1915. #endif
  1916. #ifdef SIGVTALRM
  1917. case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
  1918. #endif
  1919. #ifdef SIGPROF
  1920. case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
  1921. #endif
  1922. #ifdef SIGWINCH
  1923. case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
  1924. #endif
  1925. #ifdef SIGPOLL
  1926. case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
  1927. #endif
  1928. #ifdef SIGIO
  1929. # if !defined(SIGPOLL) || SIGIO != SIGPOLL
  1930. case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
  1931. # endif
  1932. #endif
  1933. #ifdef SIGPWR
  1934. case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
  1935. #endif
  1936. #ifdef SIGSYS
  1937. case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
  1938. #endif
  1939. #ifdef SIGUNUSED
  1940. # if !defined(SIGSYS) || SIGUNUSED != SIGSYS
  1941. case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
  1942. # endif
  1943. #endif
  1944. default:
  1945. cp->ExitException = kwsysProcess_Exception_Other;
  1946. sprintf(cp->ExitExceptionString, "Signal %d", sig);
  1947. break;
  1948. }
  1949. }
  1950. #undef KWSYSPE_CASE
  1951. /*--------------------------------------------------------------------------*/
  1952. /* When the child process encounters an error before its program is
  1953. invoked, this is called to report the error to the parent and
  1954. exit. */
  1955. static void kwsysProcessChildErrorExit(int errorPipe)
  1956. {
  1957. /* Construct the error message. */
  1958. char buffer[KWSYSPE_PIPE_BUFFER_SIZE];
  1959. kwsysProcess_ssize_t result;
  1960. strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
  1961. /* Report the error to the parent through the special pipe. */
  1962. result=write(errorPipe, buffer, strlen(buffer));
  1963. (void)result;
  1964. /* Terminate without cleanup. */
  1965. _exit(1);
  1966. }
  1967. /*--------------------------------------------------------------------------*/
  1968. /* Restores all signal handlers to their default values. */
  1969. static void kwsysProcessRestoreDefaultSignalHandlers(void)
  1970. {
  1971. struct sigaction act;
  1972. memset(&act, 0, sizeof(struct sigaction));
  1973. act.sa_handler = SIG_DFL;
  1974. #ifdef SIGHUP
  1975. sigaction(SIGHUP, &act, 0);
  1976. #endif
  1977. #ifdef SIGINT
  1978. sigaction(SIGINT, &act, 0);
  1979. #endif
  1980. #ifdef SIGQUIT
  1981. sigaction(SIGQUIT, &act, 0);
  1982. #endif
  1983. #ifdef SIGILL
  1984. sigaction(SIGILL, &act, 0);
  1985. #endif
  1986. #ifdef SIGTRAP
  1987. sigaction(SIGTRAP, &act, 0);
  1988. #endif
  1989. #ifdef SIGABRT
  1990. sigaction(SIGABRT, &act, 0);
  1991. #endif
  1992. #ifdef SIGIOT
  1993. sigaction(SIGIOT, &act, 0);
  1994. #endif
  1995. #ifdef SIGBUS
  1996. sigaction(SIGBUS, &act, 0);
  1997. #endif
  1998. #ifdef SIGFPE
  1999. sigaction(SIGFPE, &act, 0);
  2000. #endif
  2001. #ifdef SIGUSR1
  2002. sigaction(SIGUSR1, &act, 0);
  2003. #endif
  2004. #ifdef SIGSEGV
  2005. sigaction(SIGSEGV, &act, 0);
  2006. #endif
  2007. #ifdef SIGUSR2
  2008. sigaction(SIGUSR2, &act, 0);
  2009. #endif
  2010. #ifdef SIGPIPE
  2011. sigaction(SIGPIPE, &act, 0);
  2012. #endif
  2013. #ifdef SIGALRM
  2014. sigaction(SIGALRM, &act, 0);
  2015. #endif
  2016. #ifdef SIGTERM
  2017. sigaction(SIGTERM, &act, 0);
  2018. #endif
  2019. #ifdef SIGSTKFLT
  2020. sigaction(SIGSTKFLT, &act, 0);
  2021. #endif
  2022. #ifdef SIGCLD
  2023. sigaction(SIGCLD, &act, 0);
  2024. #endif
  2025. #ifdef SIGCHLD
  2026. sigaction(SIGCHLD, &act, 0);
  2027. #endif
  2028. #ifdef SIGCONT
  2029. sigaction(SIGCONT, &act, 0);
  2030. #endif
  2031. #ifdef SIGTSTP
  2032. sigaction(SIGTSTP, &act, 0);
  2033. #endif
  2034. #ifdef SIGTTIN
  2035. sigaction(SIGTTIN, &act, 0);
  2036. #endif
  2037. #ifdef SIGTTOU
  2038. sigaction(SIGTTOU, &act, 0);
  2039. #endif
  2040. #ifdef SIGURG
  2041. sigaction(SIGURG, &act, 0);
  2042. #endif
  2043. #ifdef SIGXCPU
  2044. sigaction(SIGXCPU, &act, 0);
  2045. #endif
  2046. #ifdef SIGXFSZ
  2047. sigaction(SIGXFSZ, &act, 0);
  2048. #endif
  2049. #ifdef SIGVTALRM
  2050. sigaction(SIGVTALRM, &act, 0);
  2051. #endif
  2052. #ifdef SIGPROF
  2053. sigaction(SIGPROF, &act, 0);
  2054. #endif
  2055. #ifdef SIGWINCH
  2056. sigaction(SIGWINCH, &act, 0);
  2057. #endif
  2058. #ifdef SIGPOLL
  2059. sigaction(SIGPOLL, &act, 0);
  2060. #endif
  2061. #ifdef SIGIO
  2062. sigaction(SIGIO, &act, 0);
  2063. #endif
  2064. #ifdef SIGPWR
  2065. sigaction(SIGPWR, &act, 0);
  2066. #endif
  2067. #ifdef SIGSYS
  2068. sigaction(SIGSYS, &act, 0);
  2069. #endif
  2070. #ifdef SIGUNUSED
  2071. sigaction(SIGUNUSED, &act, 0);
  2072. #endif
  2073. }
  2074. /*--------------------------------------------------------------------------*/
  2075. static void kwsysProcessExit(void)
  2076. {
  2077. _exit(0);
  2078. }
  2079. /*--------------------------------------------------------------------------*/
  2080. #if !defined(__VMS)
  2081. static pid_t kwsysProcessFork(kwsysProcess* cp,
  2082. kwsysProcessCreateInformation* si)
  2083. {
  2084. /* Create a detached process if requested. */
  2085. if(cp->OptionDetach)
  2086. {
  2087. /* Create an intermediate process. */
  2088. pid_t middle_pid = fork();
  2089. if(middle_pid < 0)
  2090. {
  2091. /* Fork failed. Return as if we were not detaching. */
  2092. return middle_pid;
  2093. }
  2094. else if(middle_pid == 0)
  2095. {
  2096. /* This is the intermediate process. Create the real child. */
  2097. pid_t child_pid = fork();
  2098. if(child_pid == 0)
  2099. {
  2100. /* This is the real child process. There is nothing to do here. */
  2101. return 0;
  2102. }
  2103. else
  2104. {
  2105. /* Use the error pipe to report the pid to the real parent. */
  2106. while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
  2107. (errno == EINTR));
  2108. /* Exit without cleanup. The parent holds all resources. */
  2109. kwsysProcessExit();
  2110. return 0; /* Never reached, but avoids SunCC warning. */
  2111. }
  2112. }
  2113. else
  2114. {
  2115. /* This is the original parent process. The intermediate
  2116. process will use the error pipe to report the pid of the
  2117. detached child. */
  2118. pid_t child_pid;
  2119. int status;
  2120. while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
  2121. (errno == EINTR));
  2122. /* Wait for the intermediate process to exit and clean it up. */
  2123. while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
  2124. return child_pid;
  2125. }
  2126. }
  2127. else
  2128. {
  2129. /* Not creating a detached process. Use normal fork. */
  2130. return fork();
  2131. }
  2132. }
  2133. #endif
  2134. /*--------------------------------------------------------------------------*/
  2135. /* We try to obtain process information by invoking the ps command.
  2136. Here we define the command to call on each platform and the
  2137. corresponding parsing format string. The parsing format should
  2138. have two integers to store: the pid and then the ppid. */
  2139. #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
  2140. # define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
  2141. # define KWSYSPE_PS_FORMAT "%d %d\n"
  2142. #elif defined(__hpux) || defined(__sun__) || defined(__sgi) || defined(_AIX) \
  2143. || defined(__sparc)
  2144. # define KWSYSPE_PS_COMMAND "ps -ef"
  2145. # define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
  2146. #elif defined(__QNX__)
  2147. # define KWSYSPE_PS_COMMAND "ps -Af"
  2148. # define KWSYSPE_PS_FORMAT "%*d %d %d %*[^\n]\n"
  2149. #elif defined(__CYGWIN__)
  2150. # define KWSYSPE_PS_COMMAND "ps aux"
  2151. # define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
  2152. #endif
  2153. /*--------------------------------------------------------------------------*/
  2154. static void kwsysProcessKill(pid_t process_id)
  2155. {
  2156. #if defined(__linux__) || defined(__CYGWIN__)
  2157. DIR* procdir;
  2158. #endif
  2159. /* Suspend the process to be sure it will not create more children. */
  2160. kill(process_id, SIGSTOP);
  2161. /* Kill all children if we can find them. */
  2162. #if defined(__linux__) || defined(__CYGWIN__)
  2163. /* First try using the /proc filesystem. */
  2164. if((procdir = opendir("/proc")) != NULL)
  2165. {
  2166. #if defined(MAXPATHLEN)
  2167. char fname[MAXPATHLEN];
  2168. #elif defined(PATH_MAX)
  2169. char fname[PATH_MAX];
  2170. #else
  2171. char fname[4096];
  2172. #endif
  2173. char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
  2174. struct dirent* d;
  2175. /* Each process has a directory in /proc whose name is the pid.
  2176. Within this directory is a file called stat that has the
  2177. following format:
  2178. pid (command line) status ppid ...
  2179. We want to get the ppid for all processes. Those that have
  2180. process_id as their parent should be recursively killed. */
  2181. for(d = readdir(procdir); d; d = readdir(procdir))
  2182. {
  2183. int pid;
  2184. if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
  2185. {
  2186. struct stat finfo;
  2187. sprintf(fname, "/proc/%d/stat", pid);
  2188. if(stat(fname, &finfo) == 0)
  2189. {
  2190. FILE* f = fopen(fname, "r");
  2191. if(f)
  2192. {
  2193. size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
  2194. buffer[nread] = '\0';
  2195. if(nread > 0)
  2196. {
  2197. const char* rparen = strrchr(buffer, ')');
  2198. int ppid;
  2199. if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
  2200. {
  2201. if(ppid == process_id)
  2202. {
  2203. /* Recursively kill this child and its children. */
  2204. kwsysProcessKill(pid);
  2205. }
  2206. }
  2207. }
  2208. fclose(f);
  2209. }
  2210. }
  2211. }
  2212. }
  2213. closedir(procdir);
  2214. }
  2215. else
  2216. #endif
  2217. {
  2218. #if defined(KWSYSPE_PS_COMMAND)
  2219. /* Try running "ps" to get the process information. */
  2220. FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
  2221. /* Make sure the process started and provided a valid header. */
  2222. if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
  2223. {
  2224. /* Look for processes whose parent is the process being killed. */
  2225. int pid, ppid;
  2226. while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
  2227. {
  2228. if(ppid == process_id)
  2229. {
  2230. /* Recursively kill this child and its children. */
  2231. kwsysProcessKill(pid);
  2232. }
  2233. }
  2234. }
  2235. /* We are done with the ps process. */
  2236. if(ps)
  2237. {
  2238. pclose(ps);
  2239. }
  2240. #endif
  2241. }
  2242. /* Kill the process. */
  2243. kill(process_id, SIGKILL);
  2244. #if defined(__APPLE__)
  2245. /* On OS X 10.3 the above SIGSTOP occasionally prevents the SIGKILL
  2246. from working. Just in case, we resume the child and kill it
  2247. again. There is a small race condition in this obscure case. If
  2248. the child manages to fork again between these two signals, we
  2249. will not catch its children. */
  2250. kill(process_id, SIGCONT);
  2251. kill(process_id, SIGKILL);
  2252. #endif
  2253. }
  2254. /*--------------------------------------------------------------------------*/
  2255. #if defined(__VMS)
  2256. int decc$feature_get_index(const char* name);
  2257. int decc$feature_set_value(int index, int mode, int value);
  2258. static int kwsysProcessSetVMSFeature(const char* name, int value)
  2259. {
  2260. int i;
  2261. errno = 0;
  2262. i = decc$feature_get_index(name);
  2263. return i >= 0 && (decc$feature_set_value(i, 1, value) >= 0 || errno == 0);
  2264. }
  2265. #endif
  2266. /*--------------------------------------------------------------------------*/
  2267. /* Global set of executing processes for use by the signal handler.
  2268. This global instance will be zero-initialized by the compiler. */
  2269. typedef struct kwsysProcessInstances_s
  2270. {
  2271. int Count;
  2272. int Size;
  2273. kwsysProcess** Processes;
  2274. } kwsysProcessInstances;
  2275. static kwsysProcessInstances kwsysProcesses;
  2276. /* The old SIGCHLD handler. */
  2277. static struct sigaction kwsysProcessesOldSigChldAction;
  2278. /*--------------------------------------------------------------------------*/
  2279. static void kwsysProcessesUpdate(kwsysProcessInstances* newProcesses)
  2280. {
  2281. /* Block SIGCHLD while we update the set of pipes to check.
  2282. TODO: sigprocmask is undefined for threaded apps. See
  2283. pthread_sigmask. */
  2284. sigset_t newset;
  2285. sigset_t oldset;
  2286. sigemptyset(&newset);
  2287. sigaddset(&newset, SIGCHLD);
  2288. sigprocmask(SIG_BLOCK, &newset, &oldset);
  2289. /* Store the new set in that seen by the signal handler. */
  2290. kwsysProcesses = *newProcesses;
  2291. /* Restore the signal mask to the previous setting. */
  2292. sigprocmask(SIG_SETMASK, &oldset, 0);
  2293. }
  2294. /*--------------------------------------------------------------------------*/
  2295. static int kwsysProcessesAdd(kwsysProcess* cp)
  2296. {
  2297. /* Create a pipe through which the signal handler can notify the
  2298. given process object that a child has exited. */
  2299. {
  2300. /* Create the pipe. */
  2301. int p[2];
  2302. if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
  2303. {
  2304. return 0;
  2305. }
  2306. /* Store the pipes now to be sure they are cleaned up later. */
  2307. cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
  2308. cp->SignalPipe = p[1];
  2309. /* Switch the pipe to non-blocking mode so that reading a byte can
  2310. be an atomic test-and-set. */
  2311. if(!kwsysProcessSetNonBlocking(p[0]) ||
  2312. !kwsysProcessSetNonBlocking(p[1]))
  2313. {
  2314. return 0;
  2315. }
  2316. /* The children do not need this pipe. Set close-on-exec flag on
  2317. the pipe's ends. */
  2318. if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
  2319. (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
  2320. {
  2321. return 0;
  2322. }
  2323. }
  2324. /* Attempt to add the given signal pipe to the signal handler set. */
  2325. {
  2326. /* Make sure there is enough space for the new signal pipe. */
  2327. kwsysProcessInstances oldProcesses = kwsysProcesses;
  2328. kwsysProcessInstances newProcesses = oldProcesses;
  2329. if(oldProcesses.Count == oldProcesses.Size)
  2330. {
  2331. /* Start with enough space for a small number of process instances
  2332. and double the size each time more is needed. */
  2333. newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
  2334. /* Try allocating the new block of memory. */
  2335. if((newProcesses.Processes = ((kwsysProcess**)
  2336. malloc((size_t)(newProcesses.Size)*
  2337. sizeof(kwsysProcess*)))))
  2338. {
  2339. /* Copy the old pipe set to the new memory. */
  2340. if(oldProcesses.Count > 0)
  2341. {
  2342. memcpy(newProcesses.Processes, oldProcesses.Processes,
  2343. ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
  2344. }
  2345. }
  2346. else
  2347. {
  2348. /* Failed to allocate memory for the new signal pipe set. */
  2349. return 0;
  2350. }
  2351. }
  2352. /* Append the new signal pipe to the set. */
  2353. newProcesses.Processes[newProcesses.Count++] = cp;
  2354. /* Store the new set in that seen by the signal handler. */
  2355. kwsysProcessesUpdate(&newProcesses);
  2356. /* Free the original pipes if new ones were allocated. */
  2357. if(newProcesses.Processes != oldProcesses.Processes)
  2358. {
  2359. free(oldProcesses.Processes);
  2360. }
  2361. /* If this is the first process, enable the signal handler. */
  2362. if(newProcesses.Count == 1)
  2363. {
  2364. /* Install our handler for SIGCHLD. Repeat call until it is not
  2365. interrupted. */
  2366. struct sigaction newSigChldAction;
  2367. memset(&newSigChldAction, 0, sizeof(struct sigaction));
  2368. #if KWSYSPE_USE_SIGINFO
  2369. newSigChldAction.sa_sigaction = kwsysProcessesSignalHandler;
  2370. newSigChldAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
  2371. # ifdef SA_RESTART
  2372. newSigChldAction.sa_flags |= SA_RESTART;
  2373. # endif
  2374. #else
  2375. newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
  2376. newSigChldAction.sa_flags = SA_NOCLDSTOP;
  2377. #endif
  2378. while((sigaction(SIGCHLD, &newSigChldAction,
  2379. &kwsysProcessesOldSigChldAction) < 0) &&
  2380. (errno == EINTR));
  2381. }
  2382. }
  2383. return 1;
  2384. }
  2385. /*--------------------------------------------------------------------------*/
  2386. static void kwsysProcessesRemove(kwsysProcess* cp)
  2387. {
  2388. /* Attempt to remove the given signal pipe from the signal handler set. */
  2389. {
  2390. /* Find the given process in the set. */
  2391. kwsysProcessInstances newProcesses = kwsysProcesses;
  2392. int i;
  2393. for(i=0; i < newProcesses.Count; ++i)
  2394. {
  2395. if(newProcesses.Processes[i] == cp)
  2396. {
  2397. break;
  2398. }
  2399. }
  2400. if(i < newProcesses.Count)
  2401. {
  2402. /* Remove the process from the set. */
  2403. --newProcesses.Count;
  2404. for(; i < newProcesses.Count; ++i)
  2405. {
  2406. newProcesses.Processes[i] = newProcesses.Processes[i+1];
  2407. }
  2408. /* If this was the last process, disable the signal handler. */
  2409. if(newProcesses.Count == 0)
  2410. {
  2411. /* Restore the SIGCHLD handler. Repeat call until it is not
  2412. interrupted. */
  2413. while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
  2414. (errno == EINTR));
  2415. /* Free the table of process pointers since it is now empty.
  2416. This is safe because the signal handler has been removed. */
  2417. newProcesses.Size = 0;
  2418. free(newProcesses.Processes);
  2419. newProcesses.Processes = 0;
  2420. }
  2421. /* Store the new set in that seen by the signal handler. */
  2422. kwsysProcessesUpdate(&newProcesses);
  2423. }
  2424. }
  2425. /* Close the pipe through which the signal handler may have notified
  2426. the given process object that a child has exited. */
  2427. kwsysProcessCleanupDescriptor(&cp->SignalPipe);
  2428. }
  2429. /*--------------------------------------------------------------------------*/
  2430. static void kwsysProcessesSignalHandler(int signum
  2431. #if KWSYSPE_USE_SIGINFO
  2432. , siginfo_t* info, void* ucontext
  2433. #endif
  2434. )
  2435. {
  2436. (void)signum;
  2437. #if KWSYSPE_USE_SIGINFO
  2438. (void)info;
  2439. (void)ucontext;
  2440. #endif
  2441. /* Signal all process objects that a child has terminated. */
  2442. {
  2443. int i;
  2444. for(i=0; i < kwsysProcesses.Count; ++i)
  2445. {
  2446. /* Set the pipe in a signalled state. */
  2447. char buf = 1;
  2448. kwsysProcess* cp = kwsysProcesses.Processes[i];
  2449. kwsysProcess_ssize_t status=
  2450. read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
  2451. status=write(cp->SignalPipe, &buf, 1);
  2452. (void)status;
  2453. }
  2454. }
  2455. #if !KWSYSPE_USE_SIGINFO
  2456. /* Re-Install our handler for SIGCHLD. Repeat call until it is not
  2457. interrupted. */
  2458. {
  2459. struct sigaction newSigChldAction;
  2460. memset(&newSigChldAction, 0, sizeof(struct sigaction));
  2461. newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
  2462. newSigChldAction.sa_flags = SA_NOCLDSTOP;
  2463. while((sigaction(SIGCHLD, &newSigChldAction,
  2464. &kwsysProcessesOldSigChldAction) < 0) &&
  2465. (errno == EINTR));
  2466. }
  2467. #endif
  2468. }