Debian Codegraph @

pTk/mTk/tclGeneric/tclPipe.c

raw symbols SCIP
1 /*
2 * tclPipe.c --
3 *
4 * This file contains the generic portion of the command channel
5 * driver as well as various utility routines used in managing
6 * subprocesses.
7 *
8 * Copyright (c) 1997 by Sun Microsystems, Inc.
9 *
10 * See the file "license.terms" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 *
13 * RCS: @(#) $Id: tclPipe.c,v 1.7 2002/12/17 02:47:39 davygrvy Exp $
14 */
15
16 #include "tclInt.h"
17 #include "tclPort.h"
18
19 /*
20 * A linked list of the following structures is used to keep track
21 * of child processes that have been detached but haven't exited
22 * yet, so we can make sure that they're properly "reaped" (officially
23 * waited for) and don't lie around as zombies cluttering the
24 * system.
25 */
26
27 typedef struct Detached {
28 Tcl_Pid pid; /* Id of process that's been detached
29 * but isn't known to have exited. */
30 struct Detached *nextPtr; /* Next in list of all detached
31 * processes. */
32 } Detached;
33
34 static Detached *detList = NULL; /* List of all detached proceses. */
35 TCL_DECLARE_MUTEX(pipeMutex) /* Guard access to detList. */
36
37 /*
38 * Declarations for local procedures defined in this file:
39 */
40
41 static TclFile FileForRedirect _ANSI_ARGS_((Tcl_Interp *interp,
42 CONST char *spec, int atOk, CONST char *arg,
43 CONST char *nextArg, int flags, int *skipPtr,
44 int *closePtr, int *releasePtr));
45
46 /*
47 *----------------------------------------------------------------------
48 *
49 * FileForRedirect --
50 *
51 * This procedure does much of the work of parsing redirection
52 * operators. It handles "@" if specified and allowed, and a file
53 * name, and opens the file if necessary.
54 *
55 * Results:
56 * The return value is the descriptor number for the file. If an
57 * error occurs then NULL is returned and an error message is left
58 * in the interp's result. Several arguments are side-effected; see
59 * the argument list below for details.
60 *
61 * Side effects:
62 * None.
63 *
64 *----------------------------------------------------------------------
65 */
66
67 static TclFile
68 FileForRedirect(interp, spec, atOK, arg, nextArg, flags, skipPtr, closePtr,
69 releasePtr)
70 Tcl_Interp *interp; /* Intepreter to use for error reporting. */
71 CONST char *spec; /* Points to character just after
72 * redirection character. */
73 CONST char *arg; /* Pointer to entire argument containing
74 * spec: used for error reporting. */
75 int atOK; /* Non-zero means that '@' notation can be
76 * used to specify a channel, zero means that
77 * it isn't. */
78 CONST char *nextArg; /* Next argument in argc/argv array, if needed
79 * for file name or channel name. May be
80 * NULL. */
81 int flags; /* Flags to use for opening file or to
82 * specify mode for channel. */
83 int *skipPtr; /* Filled with 1 if redirection target was
84 * in spec, 2 if it was in nextArg. */
85 int *closePtr; /* Filled with one if the caller should
86 * close the file when done with it, zero
87 * otherwise. */
88 int *releasePtr;
89 {
90 int writing = (flags & O_WRONLY);
91 Tcl_Channel chan;
92 TclFile file;
93
94 *skipPtr = 1;
95 if ((atOK != 0) && (*spec == '@')) {
96 spec++;
97 if (*spec == '\0') {
98 spec = nextArg;
99 if (spec == NULL) {
100 goto badLastArg;
101 }
102 *skipPtr = 2;
103 }
104 chan = Tcl_GetChannel(interp, spec, NULL);
105 if (chan == (Tcl_Channel) NULL) {
106 return NULL;
107 }
108 file = TclpMakeFile(chan, writing ? TCL_WRITABLE : TCL_READABLE);
109 if (file == NULL) {
110 Tcl_AppendResult(interp, "channel \"", Tcl_GetChannelName(chan),
111 "\" wasn't opened for ",
112 ((writing) ? "writing" : "reading"), (char *) NULL);
113 return NULL;
114 }
115 *releasePtr = 1;
116 if (writing) {
117
118 /*
119 * Be sure to flush output to the file, so that anything
120 * written by the child appears after stuff we've already
121 * written.
122 */
123
124 Tcl_Flush(chan);
125 }
126 } else {
127 CONST char *name;
128 Tcl_DString nameString;
129
130 if (*spec == '\0') {
131 spec = nextArg;
132 if (spec == NULL) {
133 goto badLastArg;
134 }
135 *skipPtr = 2;
136 }
137 name = Tcl_TranslateFileName(interp, spec, &nameString);
138 if (name != NULL) {
139 file = TclpOpenFile(name, flags);
140 } else {
141 file = NULL;
142 }
143 Tcl_DStringFree(&nameString);
144 if (file == NULL) {
145 Tcl_AppendResult(interp, "couldn't ",
146 ((writing) ? "write" : "read"), " file \"", spec, "\": ",
147 Tcl_PosixError(interp), (char *) NULL);
148 return NULL;
149 }
150 *closePtr = 1;
151 }
152 return file;
153
154 badLastArg:
155 Tcl_AppendResult(interp, "can't specify \"", arg,
156 "\" as last word in command", (char *) NULL);
157 return NULL;
158 }
159
160 /*
161 *----------------------------------------------------------------------
162 *
163 * Tcl_DetachPids --
164 *
165 * This procedure is called to indicate that one or more child
166 * processes have been placed in background and will never be
167 * waited for; they should eventually be reaped by
168 * Tcl_ReapDetachedProcs.
169 *
170 * Results:
171 * None.
172 *
173 * Side effects:
174 * None.
175 *
176 *----------------------------------------------------------------------
177 */
178
179 void
180 Tcl_DetachPids(numPids, pidPtr)
181 int numPids; /* Number of pids to detach: gives size
182 * of array pointed to by pidPtr. */
183 Tcl_Pid *pidPtr; /* Array of pids to detach. */
184 {
185 register Detached *detPtr;
186 int i;
187
188 Tcl_MutexLock(&pipeMutex);
189 for (i = 0; i < numPids; i++) {
190 detPtr = (Detached *) ckalloc(sizeof(Detached));
191 detPtr->pid = pidPtr[i];
192 detPtr->nextPtr = detList;
193 detList = detPtr;
194 }
195 Tcl_MutexUnlock(&pipeMutex);
196
197 }
198
199 /*
200 *----------------------------------------------------------------------
201 *
202 * Tcl_ReapDetachedProcs --
203 *
204 * This procedure checks to see if any detached processes have
205 * exited and, if so, it "reaps" them by officially waiting on
206 * them. It should be called "occasionally" to make sure that
207 * all detached processes are eventually reaped.
208 *
209 * Results:
210 * None.
211 *
212 * Side effects:
213 * Processes are waited on, so that they can be reaped by the
214 * system.
215 *
216 *----------------------------------------------------------------------
217 */
218
219 void
220 Tcl_ReapDetachedProcs()
221 {
222 register Detached *detPtr;
223 Detached *nextPtr, *prevPtr;
224 int status;
225 Tcl_Pid pid;
226
227 Tcl_MutexLock(&pipeMutex);
228 for (detPtr = detList, prevPtr = NULL; detPtr != NULL; ) {
229 pid = Tcl_WaitPid(detPtr->pid, &status, WNOHANG);
230 if ((pid == 0) || ((pid == (Tcl_Pid) -1) && (errno != ECHILD))) {
231 prevPtr = detPtr;
232 detPtr = detPtr->nextPtr;
233 continue;
234 }
235 nextPtr = detPtr->nextPtr;
236 if (prevPtr == NULL) {
237 detList = detPtr->nextPtr;
238 } else {
239 prevPtr->nextPtr = detPtr->nextPtr;
240 }
241 ckfree((char *) detPtr);
242 detPtr = nextPtr;
243 }
244 Tcl_MutexUnlock(&pipeMutex);
245 }
246
247 /*
248 *----------------------------------------------------------------------
249 *
250 * TclCleanupChildren --
251 *
252 * This is a utility procedure used to wait for child processes
253 * to exit, record information about abnormal exits, and then
254 * collect any stderr output generated by them.
255 *
256 * Results:
257 * The return value is a standard Tcl result. If anything at
258 * weird happened with the child processes, TCL_ERROR is returned
259 * and a message is left in the interp's result.
260 *
261 * Side effects:
262 * If the last character of the interp's result is a newline, then it
263 * is removed unless keepNewline is non-zero. File errorId gets
264 * closed, and pidPtr is freed back to the storage allocator.
265 *
266 *----------------------------------------------------------------------
267 */
268
269 int
270 TclCleanupChildren(interp, numPids, pidPtr, errorChan)
271 Tcl_Interp *interp; /* Used for error messages. */
272 int numPids; /* Number of entries in pidPtr array. */
273 Tcl_Pid *pidPtr; /* Array of process ids of children. */
274 Tcl_Channel errorChan; /* Channel for file containing stderr output
275 * from pipeline. NULL means there isn't any
276 * stderr output. */
277 {
278 int result = TCL_OK;
279 int i, abnormalExit, anyErrorInfo;
280 Tcl_Pid pid;
281 WAIT_STATUS_TYPE waitStatus;
282 CONST char *msg;
283 unsigned long resolvedPid;
284
285 abnormalExit = 0;
286 for (i = 0; i < numPids; i++) {
287 /*
288 * We need to get the resolved pid before we wait on it as
289 * the windows implimentation of Tcl_WaitPid deletes the
290 * information such that any following calls to TclpGetPid
291 * fail.
292 */
293 resolvedPid = TclpGetPid(pidPtr[i]);
294 pid = Tcl_WaitPid(pidPtr[i], (int *) &waitStatus, 0);
295 if (pid == (Tcl_Pid) -1) {
296 result = TCL_ERROR;
297 if (interp != (Tcl_Interp *) NULL) {
298 msg = Tcl_PosixError(interp);
299 if (errno == ECHILD) {
300 /*
301 * This changeup in message suggested by Mark Diekhans
302 * to remind people that ECHILD errors can occur on
303 * some systems if SIGCHLD isn't in its default state.
304 */
305
306 msg =
307 "child process lost (is SIGCHLD ignored or trapped?)";
308 }
309 Tcl_AppendResult(interp, "error waiting for process to exit: ",
310 msg, (char *) NULL);
311 }
312 continue;
313 }
314
315 /*
316 * Create error messages for unusual process exits. An
317 * extra newline gets appended to each error message, but
318 * it gets removed below (in the same fashion that an
319 * extra newline in the command's output is removed).
320 */
321
322 if (!WIFEXITED(waitStatus) || (WEXITSTATUS(waitStatus) != 0)) {
323 char msg1[TCL_INTEGER_SPACE], msg2[TCL_INTEGER_SPACE];
324
325 result = TCL_ERROR;
326 TclFormatInt(msg1, (long) resolvedPid);
327 if (WIFEXITED(waitStatus)) {
328 if (interp != (Tcl_Interp *) NULL) {
329 TclFormatInt(msg2, WEXITSTATUS(waitStatus));
330 Tcl_SetErrorCode(interp, "CHILDSTATUS", msg1, msg2,
331 (char *) NULL);
332 }
333 abnormalExit = 1;
334 } else if (WIFSIGNALED(waitStatus)) {
335 if (interp != (Tcl_Interp *) NULL) {
336 CONST char *p;
337
338 p = Tcl_SignalMsg((int) (WTERMSIG(waitStatus)));
339 Tcl_SetErrorCode(interp, "CHILDKILLED", msg1,
340 Tcl_SignalId((int) (WTERMSIG(waitStatus))), p,
341 (char *) NULL);
342 Tcl_AppendResult(interp, "child killed: ", p, "\n",
343 (char *) NULL);
344 }
345 } else if (WIFSTOPPED(waitStatus)) {
346 if (interp != (Tcl_Interp *) NULL) {
347 CONST char *p;
348
349 p = Tcl_SignalMsg((int) (WSTOPSIG(waitStatus)));
350 Tcl_SetErrorCode(interp, "CHILDSUSP", msg1,
351 Tcl_SignalId((int) (WSTOPSIG(waitStatus))),
352 p, (char *) NULL);
353 Tcl_AppendResult(interp, "child suspended: ", p, "\n",
354 (char *) NULL);
355 }
356 } else {
357 if (interp != (Tcl_Interp *) NULL) {
358 Tcl_AppendResult(interp,
359 "child wait status didn't make sense\n",
360 (char *) NULL);
361 }
362 }
363 }
364 }
365
366 /*
367 * Read the standard error file. If there's anything there,
368 * then return an error and add the file's contents to the result
369 * string.
370 */
371
372 anyErrorInfo = 0;
373 if (errorChan != NULL) {
374
375 /*
376 * Make sure we start at the beginning of the file.
377 */
378
379 if (interp != NULL) {
380 int count;
381 Tcl_Obj *objPtr;
382
383 Tcl_Seek(errorChan, (Tcl_WideInt)0, SEEK_SET);
384 objPtr = Tcl_NewObj();
385 count = Tcl_ReadChars(errorChan, objPtr, -1, 0);
386 if (count < 0) {
387 result = TCL_ERROR;
388 Tcl_DecrRefCount(objPtr);
389 Tcl_ResetResult(interp);
390 Tcl_AppendResult(interp, "error reading stderr output file: ",
391 Tcl_PosixError(interp), NULL);
392 } else if (count > 0) {
393 anyErrorInfo = 1;
394 Tcl_SetObjResult(interp, objPtr);
395 result = TCL_ERROR;
396 } else {
397 Tcl_DecrRefCount(objPtr);
398 }
399 }
400 Tcl_Close(NULL, errorChan);
401 }
402
403 /*
404 * If a child exited abnormally but didn't output any error information
405 * at all, generate an error message here.
406 */
407
408 if ((abnormalExit != 0) && (anyErrorInfo == 0) && (interp != NULL)) {
409 Tcl_AppendResult(interp, "child process exited abnormally",
410 (char *) NULL);
411 }
412 return result;
413 }
414
415 /*
416 *----------------------------------------------------------------------
417 *
418 * TclCreatePipeline --
419 *
420 * Given an argc/argv array, instantiate a pipeline of processes
421 * as described by the argv.
422 *
423 * This procedure is unofficially exported for use by BLT.
424 *
425 * Results:
426 * The return value is a count of the number of new processes
427 * created, or -1 if an error occurred while creating the pipeline.
428 * *pidArrayPtr is filled in with the address of a dynamically
429 * allocated array giving the ids of all of the processes. It
430 * is up to the caller to free this array when it isn't needed
431 * anymore. If inPipePtr is non-NULL, *inPipePtr is filled in
432 * with the file id for the input pipe for the pipeline (if any):
433 * the caller must eventually close this file. If outPipePtr
434 * isn't NULL, then *outPipePtr is filled in with the file id
435 * for the output pipe from the pipeline: the caller must close
436 * this file. If errFilePtr isn't NULL, then *errFilePtr is filled
437 * with a file id that may be used to read error output after the
438 * pipeline completes.
439 *
440 * Side effects:
441 * Processes and pipes are created.
442 *
443 *----------------------------------------------------------------------
444 */
445
446 int
447 TclCreatePipeline(interp, argc, argv, pidArrayPtr, inPipePtr,
448 outPipePtr, errFilePtr)
449 Tcl_Interp *interp; /* Interpreter to use for error reporting. */
450 int argc; /* Number of entries in argv. */
451 CONST char **argv; /* Array of strings describing commands in
452 * pipeline plus I/O redirection with <,
453 * <<, >, etc. Argv[argc] must be NULL. */
454 Tcl_Pid **pidArrayPtr; /* Word at *pidArrayPtr gets filled in with
455 * address of array of pids for processes
456 * in pipeline (first pid is first process
457 * in pipeline). */
458 TclFile *inPipePtr; /* If non-NULL, input to the pipeline comes
459 * from a pipe (unless overridden by
460 * redirection in the command). The file
461 * id with which to write to this pipe is
462 * stored at *inPipePtr. NULL means command
463 * specified its own input source. */
464 TclFile *outPipePtr; /* If non-NULL, output to the pipeline goes
465 * to a pipe, unless overriden by redirection
466 * in the command. The file id with which to
467 * read frome this pipe is stored at
468 * *outPipePtr. NULL means command specified
469 * its own output sink. */
470 TclFile *errFilePtr; /* If non-NULL, all stderr output from the
471 * pipeline will go to a temporary file
472 * created here, and a descriptor to read
473 * the file will be left at *errFilePtr.
474 * The file will be removed already, so
475 * closing this descriptor will be the end
476 * of the file. If this is NULL, then
477 * all stderr output goes to our stderr.
478 * If the pipeline specifies redirection
479 * then the file will still be created
480 * but it will never get any data. */
481 {
482 Tcl_Pid *pidPtr = NULL; /* Points to malloc-ed array holding all
483 * the pids of child processes. */
484 int numPids; /* Actual number of processes that exist
485 * at *pidPtr right now. */
486 int cmdCount; /* Count of number of distinct commands
487 * found in argc/argv. */
488 CONST char *inputLiteral = NULL; /* If non-null, then this points to a
489 * string containing input data (specified
490 * via <<) to be piped to the first process
491 * in the pipeline. */
492 TclFile inputFile = NULL; /* If != NULL, gives file to use as input for
493 * first process in pipeline (specified via <
494 * or <@). */
495 int inputClose = 0; /* If non-zero, then inputFile should be
496 * closed when cleaning up. */
497 int inputRelease = 0;
498 TclFile outputFile = NULL; /* Writable file for output from last command
499 * in pipeline (could be file or pipe). NULL
500 * means use stdout. */
501 int outputClose = 0; /* If non-zero, then outputFile should be
502 * closed when cleaning up. */
503 int outputRelease = 0;
504 TclFile errorFile = NULL; /* Writable file for error output from all
505 * commands in pipeline. NULL means use
506 * stderr. */
507 int errorClose = 0; /* If non-zero, then errorFile should be
508 * closed when cleaning up. */
509 int errorRelease = 0;
510 CONST char *p;
511 int skip, lastBar, lastArg, i, j, atOK, flags, errorToOutput;
512 Tcl_DString execBuffer;
513 TclFile pipeIn;
514 TclFile curInFile, curOutFile, curErrFile;
515 Tcl_Channel channel;
516
517 if (inPipePtr != NULL) {
518 *inPipePtr = NULL;
519 }
520 if (outPipePtr != NULL) {
521 *outPipePtr = NULL;
522 }
523 if (errFilePtr != NULL) {
524 *errFilePtr = NULL;
525 }
526
527 Tcl_DStringInit(&execBuffer);
528
529 pipeIn = NULL;
530 curInFile = NULL;
531 curOutFile = NULL;
532 numPids = 0;
533
534 /*
535 * First, scan through all the arguments to figure out the structure
536 * of the pipeline. Process all of the input and output redirection
537 * arguments and remove them from the argument list in the pipeline.
538 * Count the number of distinct processes (it's the number of "|"
539 * arguments plus one) but don't remove the "|" arguments because
540 * they'll be used in the second pass to seperate the individual
541 * child processes. Cannot start the child processes in this pass
542 * because the redirection symbols may appear anywhere in the
543 * command line -- e.g., the '<' that specifies the input to the
544 * entire pipe may appear at the very end of the argument list.
545 */
546
547 lastBar = -1;
548 cmdCount = 1;
549 for (i = 0; i < argc; i++) {
550 skip = 0;
551 p = argv[i];
552 switch (*p++) {
553 case '|':
554 if (*p == '&') {
555 p++;
556 }
557 if (*p == '\0') {
558 if ((i == (lastBar + 1)) || (i == (argc - 1))) {
559 Tcl_SetResult(interp,
560 "illegal use of | or |& in command",
561 TCL_STATIC);
562 goto error;
563 }
564 }
565 lastBar = i;
566 cmdCount++;
567 break;
568
569 case '<':
570 if (inputClose != 0) {
571 inputClose = 0;
572 TclpCloseFile(inputFile);
573 }
574 if (inputRelease != 0) {
575 inputRelease = 0;
576 TclpReleaseFile(inputFile);
577 }
578 if (*p == '<') {
579 inputFile = NULL;
580 inputLiteral = p + 1;
581 skip = 1;
582 if (*inputLiteral == '\0') {
583 inputLiteral = argv[i + 1];
584 if (inputLiteral == NULL) {
585 Tcl_AppendResult(interp, "can't specify \"", argv[i],
586 "\" as last word in command", (char *) NULL);
587 goto error;
588 }
589 skip = 2;
590 }
591 } else {
592 inputLiteral = NULL;
593 inputFile = FileForRedirect(interp, p, 1, argv[i],
594 argv[i + 1], O_RDONLY, &skip, &inputClose, &inputRelease);
595 if (inputFile == NULL) {
596 goto error;
597 }
598 }
599 break;
600
601 case '>':
602 atOK = 1;
603 flags = O_WRONLY | O_CREAT | O_TRUNC;
604 errorToOutput = 0;
605 if (*p == '>') {
606 p++;
607 atOK = 0;
608 flags = O_WRONLY | O_CREAT;
609 }
610 if (*p == '&') {
611 if (errorClose != 0) {
612 errorClose = 0;
613 TclpCloseFile(errorFile);
614 }
615 errorToOutput = 1;
616 p++;
617 }
618
619 /*
620 * Close the old output file, but only if the error file is
621 * not also using it.
622 */
623
624 if (outputClose != 0) {
625 outputClose = 0;
626 if (errorFile == outputFile) {
627 errorClose = 1;
628 } else {
629 TclpCloseFile(outputFile);
630 }
631 }
632 if (outputRelease != 0) {
633 outputRelease = 0;
634 if (errorFile == outputFile) {
635 errorRelease = 1;
636 } else {
637 TclpReleaseFile(outputFile);
638 }
639 }
640 outputFile = FileForRedirect(interp, p, atOK, argv[i],
641 argv[i + 1], flags, &skip, &outputClose, &outputRelease);
642 if (outputFile == NULL) {
643 goto error;
644 }
645 if (errorToOutput) {
646 if (errorClose != 0) {
647 errorClose = 0;
648 TclpCloseFile(errorFile);
649 }
650 if (errorRelease != 0) {
651 errorRelease = 0;
652 TclpReleaseFile(errorFile);
653 }
654 errorFile = outputFile;
655 }
656 break;
657
658 case '2':
659 if (*p != '>') {
660 break;
661 }
662 p++;
663 atOK = 1;
664 flags = O_WRONLY | O_CREAT | O_TRUNC;
665 if (*p == '>') {
666 p++;
667 atOK = 0;
668 flags = O_WRONLY | O_CREAT;
669 }
670 if (errorClose != 0) {
671 errorClose = 0;
672 TclpCloseFile(errorFile);
673 }
674 if (errorRelease != 0) {
675 errorRelease = 0;
676 TclpReleaseFile(errorFile);
677 }
678 errorFile = FileForRedirect(interp, p, atOK, argv[i],
679 argv[i + 1], flags, &skip, &errorClose, &errorRelease);
680 if (errorFile == NULL) {
681 goto error;
682 }
683 break;
684 }
685
686 if (skip != 0) {
687 for (j = i + skip; j < argc; j++) {
688 argv[j - skip] = argv[j];
689 }
690 argc -= skip;
691 i -= 1;
692 }
693 }
694
695 if (inputFile == NULL) {
696 if (inputLiteral != NULL) {
697 /*
698 * The input for the first process is immediate data coming from
699 * Tcl. Create a temporary file for it and put the data into the
700 * file.
701 */
702 inputFile = TclpCreateTempFile(inputLiteral);
703 if (inputFile == NULL) {
704 Tcl_AppendResult(interp,
705 "couldn't create input file for command: ",
706 Tcl_PosixError(interp), (char *) NULL);
707 goto error;
708 }
709 inputClose = 1;
710 } else if (inPipePtr != NULL) {
711 /*
712 * The input for the first process in the pipeline is to
713 * come from a pipe that can be written from by the caller.
714 */
715
716 if (TclpCreatePipe(&inputFile, inPipePtr) == 0) {
717 Tcl_AppendResult(interp,
718 "couldn't create input pipe for command: ",
719 Tcl_PosixError(interp), (char *) NULL);
720 goto error;
721 }
722 inputClose = 1;
723 } else {
724 /*
725 * The input for the first process comes from stdin.
726 */
727
728 channel = Tcl_GetStdChannel(TCL_STDIN);
729 if (channel != NULL) {
730 inputFile = TclpMakeFile(channel, TCL_READABLE);
731 if (inputFile != NULL) {
732 inputRelease = 1;
733 }
734 }
735 }
736 }
737
738 if (outputFile == NULL) {
739 if (outPipePtr != NULL) {
740 /*
741 * Output from the last process in the pipeline is to go to a
742 * pipe that can be read by the caller.
743 */
744
745 if (TclpCreatePipe(outPipePtr, &outputFile) == 0) {
746 Tcl_AppendResult(interp,
747 "couldn't create output pipe for command: ",
748 Tcl_PosixError(interp), (char *) NULL);
749 goto error;
750 }
751 outputClose = 1;
752 } else {
753 /*
754 * The output for the last process goes to stdout.
755 */
756
757 channel = Tcl_GetStdChannel(TCL_STDOUT);
758 if (channel) {
759 outputFile = TclpMakeFile(channel, TCL_WRITABLE);
760 if (outputFile != NULL) {
761 outputRelease = 1;
762 }
763 }
764 }
765 }
766
767 if (errorFile == NULL) {
768 if (errFilePtr != NULL) {
769 /*
770 * Set up the standard error output sink for the pipeline, if
771 * requested. Use a temporary file which is opened, then deleted.
772 * Could potentially just use pipe, but if it filled up it could
773 * cause the pipeline to deadlock: we'd be waiting for processes
774 * to complete before reading stderr, and processes couldn't
775 * complete because stderr was backed up.
776 */
777
778 errorFile = TclpCreateTempFile(NULL);
779 if (errorFile == NULL) {
780 Tcl_AppendResult(interp,
781 "couldn't create error file for command: ",
782 Tcl_PosixError(interp), (char *) NULL);
783 goto error;
784 }
785 *errFilePtr = errorFile;
786 } else {
787 /*
788 * Errors from the pipeline go to stderr.
789 */
790
791 channel = Tcl_GetStdChannel(TCL_STDERR);
792 if (channel) {
793 errorFile = TclpMakeFile(channel, TCL_WRITABLE);
794 if (errorFile != NULL) {
795 errorRelease = 1;
796 }
797 }
798 }
799 }
800
801 /*
802 * Scan through the argc array, creating a process for each
803 * group of arguments between the "|" characters.
804 */
805
806 Tcl_ReapDetachedProcs();
807 pidPtr = (Tcl_Pid *) ckalloc((unsigned) (cmdCount * sizeof(Tcl_Pid)));
808
809 curInFile = inputFile;
810
811 for (i = 0; i < argc; i = lastArg + 1) {
812 int result, joinThisError;
813 Tcl_Pid pid;
814 CONST char *oldName;
815
816 /*
817 * Convert the program name into native form.
818 */
819
820 if (Tcl_TranslateFileName(interp, argv[i], &execBuffer) == NULL) {
821 goto error;
822 }
823
824 /*
825 * Find the end of the current segment of the pipeline.
826 */
827
828 joinThisError = 0;
829 for (lastArg = i; lastArg < argc; lastArg++) {
830 if (argv[lastArg][0] == '|') {
831 if (argv[lastArg][1] == '\0') {
832 break;
833 }
834 if ((argv[lastArg][1] == '&') && (argv[lastArg][2] == '\0')) {
835 joinThisError = 1;
836 break;
837 }
838 }
839 }
840 argv[lastArg] = NULL;
841
842 /*
843 * If this is the last segment, use the specified outputFile.
844 * Otherwise create an intermediate pipe. pipeIn will become the
845 * curInFile for the next segment of the pipe.
846 */
847
848 if (lastArg == argc) {
849 curOutFile = outputFile;
850 } else {
851 if (TclpCreatePipe(&pipeIn, &curOutFile) == 0) {
852 Tcl_AppendResult(interp, "couldn't create pipe: ",
853 Tcl_PosixError(interp), (char *) NULL);
854 goto error;
855 }
856 }
857
858 if (joinThisError != 0) {
859 curErrFile = curOutFile;
860 } else {
861 curErrFile = errorFile;
862 }
863
864 /*
865 * Restore argv[i], since a caller wouldn't expect the contents of
866 * argv to be modified.
867 */
868
869 oldName = argv[i];
870 argv[i] = Tcl_DStringValue(&execBuffer);
871 result = TclpCreateProcess(interp, lastArg - i, argv + i,
872 curInFile, curOutFile, curErrFile, &pid);
873 argv[i] = oldName;
874 if (result != TCL_OK) {
875 goto error;
876 }
877 Tcl_DStringFree(&execBuffer);
878
879 pidPtr[numPids] = pid;
880 numPids++;
881
882 /*
883 * Close off our copies of file descriptors that were set up for
884 * this child, then set up the input for the next child.
885 */
886
887 if ((curInFile != NULL) && (curInFile != inputFile)) {
888 TclpCloseFile(curInFile);
889 }
890 curInFile = pipeIn;
891 pipeIn = NULL;
892
893 if ((curOutFile != NULL) && (curOutFile != outputFile)) {
894 TclpCloseFile(curOutFile);
895 }
896 curOutFile = NULL;
897 }
898
899 *pidArrayPtr = pidPtr;
900
901 /*
902 * All done. Cleanup open files lying around and then return.
903 */
904
905 cleanup:
906 Tcl_DStringFree(&execBuffer);
907
908 if (inputClose) {
909 TclpCloseFile(inputFile);
910 } else if (inputRelease) {
911 TclpReleaseFile(inputFile);
912 }
913 if (outputClose) {
914 TclpCloseFile(outputFile);
915 } else if (outputRelease) {
916 TclpReleaseFile(outputFile);
917 }
918 if (errorClose) {
919 TclpCloseFile(errorFile);
920 } else if (errorRelease) {
921 TclpReleaseFile(errorFile);
922 }
923 return numPids;
924
925 /*
926 * An error occurred. There could have been extra files open, such
927 * as pipes between children. Clean them all up. Detach any child
928 * processes that have been created.
929 */
930
931 error:
932 if (pipeIn != NULL) {
933 TclpCloseFile(pipeIn);
934 }
935 if ((curOutFile != NULL) && (curOutFile != outputFile)) {
936 TclpCloseFile(curOutFile);
937 }
938 if ((curInFile != NULL) && (curInFile != inputFile)) {
939 TclpCloseFile(curInFile);
940 }
941 if ((inPipePtr != NULL) && (*inPipePtr != NULL)) {
942 TclpCloseFile(*inPipePtr);
943 *inPipePtr = NULL;
944 }
945 if ((outPipePtr != NULL) && (*outPipePtr != NULL)) {
946 TclpCloseFile(*outPipePtr);
947 *outPipePtr = NULL;
948 }
949 if ((errFilePtr != NULL) && (*errFilePtr != NULL)) {
950 TclpCloseFile(*errFilePtr);
951 *errFilePtr = NULL;
952 }
953 if (pidPtr != NULL) {
954 for (i = 0; i < numPids; i++) {
955 if (pidPtr[i] != (Tcl_Pid) -1) {
956 Tcl_DetachPids(1, &pidPtr[i]);
957 }
958 }
959 ckfree((char *) pidPtr);
960 }
961 numPids = -1;
962 goto cleanup;
963 }
964
965 /*
966 *----------------------------------------------------------------------
967 *
968 * Tcl_OpenCommandChannel --
969 *
970 * Opens an I/O channel to one or more subprocesses specified
971 * by argc and argv. The flags argument determines the
972 * disposition of the stdio handles. If the TCL_STDIN flag is
973 * set then the standard input for the first subprocess will
974 * be tied to the channel: writing to the channel will provide
975 * input to the subprocess. If TCL_STDIN is not set, then
976 * standard input for the first subprocess will be the same as
977 * this application's standard input. If TCL_STDOUT is set then
978 * standard output from the last subprocess can be read from the
979 * channel; otherwise it goes to this application's standard
980 * output. If TCL_STDERR is set, standard error output for all
981 * subprocesses is returned to the channel and results in an error
982 * when the channel is closed; otherwise it goes to this
983 * application's standard error. If TCL_ENFORCE_MODE is not set,
984 * then argc and argv can redirect the stdio handles to override
985 * TCL_STDIN, TCL_STDOUT, and TCL_STDERR; if it is set, then it
986 * is an error for argc and argv to override stdio channels for
987 * which TCL_STDIN, TCL_STDOUT, and TCL_STDERR have been set.
988 *
989 * Results:
990 * A new command channel, or NULL on failure with an error
991 * message left in interp.
992 *
993 * Side effects:
994 * Creates processes, opens pipes.
995 *
996 *----------------------------------------------------------------------
997 */
998
999 Tcl_Channel
1000 Tcl_OpenCommandChannel(interp, argc, argv, flags)
1001 Tcl_Interp *interp; /* Interpreter for error reporting. Can
1002 * NOT be NULL. */
1003 int argc; /* How many arguments. */
1004 CONST char **argv; /* Array of arguments for command pipe. */
1005 int flags; /* Or'ed combination of TCL_STDIN, TCL_STDOUT,
1006 * TCL_STDERR, and TCL_ENFORCE_MODE. */
1007 {
1008 TclFile *inPipePtr, *outPipePtr, *errFilePtr;
1009 TclFile inPipe, outPipe, errFile;
1010 int numPids;
1011 Tcl_Pid *pidPtr;
1012 Tcl_Channel channel;
1013
1014 inPipe = outPipe = errFile = NULL;
1015
1016 inPipePtr = (flags & TCL_STDIN) ? &inPipe : NULL;
1017 outPipePtr = (flags & TCL_STDOUT) ? &outPipe : NULL;
1018 errFilePtr = (flags & TCL_STDERR) ? &errFile : NULL;
1019
1020 numPids = TclCreatePipeline(interp, argc, argv, &pidPtr, inPipePtr,
1021 outPipePtr, errFilePtr);
1022
1023 if (numPids < 0) {
1024 goto error;
1025 }
1026
1027 /*
1028 * Verify that the pipes that were created satisfy the
1029 * readable/writable constraints.
1030 */
1031
1032 if (flags & TCL_ENFORCE_MODE) {
1033 if ((flags & TCL_STDOUT) && (outPipe == NULL)) {
1034 Tcl_AppendResult(interp, "can't read output from command:",
1035 " standard output was redirected", (char *) NULL);
1036 goto error;
1037 }
1038 if ((flags & TCL_STDIN) && (inPipe == NULL)) {
1039 Tcl_AppendResult(interp, "can't write input to command:",
1040 " standard input was redirected", (char *) NULL);
1041 goto error;
1042 }
1043 }
1044
1045 channel = TclpCreateCommandChannel(outPipe, inPipe, errFile,
1046 numPids, pidPtr);
1047
1048 if (channel == (Tcl_Channel) NULL) {
1049 Tcl_AppendResult(interp, "pipe for command could not be created",
1050 (char *) NULL);
1051 goto error;
1052 }
1053 return channel;
1054
1055 error:
1056 if (numPids > 0) {
1057 Tcl_DetachPids(numPids, pidPtr);
1058 ckfree((char *) pidPtr);
1059 }
1060 if (inPipe != NULL) {
1061 TclpCloseFile(inPipe);
1062 }
1063 if (outPipe != NULL) {
1064 TclpCloseFile(outPipe);
1065 }
1066 if (errFile != NULL) {
1067 TclpCloseFile(errFile);
1068 }
1069 return NULL;
1070 }