Debian Codegraph @

pTk/mTk/tclUnix/tclUnixPipe.c

raw symbols SCIP
1 /*
2 * tclUnixPipe.c --
3 *
4 * This file implements the UNIX-specific exec pipeline functions,
5 * the "pipe" channel driver, and the "pid" Tcl command.
6 *
7 * Copyright (c) 1991-1994 The Regents of the University of California.
8 * Copyright (c) 1994-1997 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: tclUnixPipe.c,v 1.23 2003/02/21 14:15:58 das Exp $
14 */
15
16 #include "tclInt.h"
17 #include "tclPort.h"
18
19 #ifdef USE_VFORK
20 #define fork vfork
21 #endif
22
23 /*
24 * The following macros convert between TclFile's and fd's. The conversion
25 * simple involves shifting fd's up by one to ensure that no valid fd is ever
26 * the same as NULL.
27 */
28
29 #define MakeFile(fd) ((TclFile)(((int)fd)+1))
30 #define GetFd(file) (((int)file)-1)
31
32 /*
33 * This structure describes per-instance state of a pipe based channel.
34 */
35
36 typedef struct PipeState {
37 Tcl_Channel channel;/* Channel associated with this file. */
38 TclFile inFile; /* Output from pipe. */
39 TclFile outFile; /* Input to pipe. */
40 TclFile errorFile; /* Error output from pipe. */
41 int numPids; /* How many processes are attached to this pipe? */
42 Tcl_Pid *pidPtr; /* The process IDs themselves. Allocated by
43 * the creator of the pipe. */
44 int isNonBlocking; /* Nonzero when the pipe is in nonblocking mode.
45 * Used to decide whether to wait for the children
46 * at close time. */
47 } PipeState;
48
49 /*
50 * Declarations for local procedures defined in this file:
51 */
52
53 static int PipeBlockModeProc _ANSI_ARGS_((ClientData instanceData,
54 int mode));
55 static int PipeCloseProc _ANSI_ARGS_((ClientData instanceData,
56 Tcl_Interp *interp));
57 static int PipeGetHandleProc _ANSI_ARGS_((ClientData instanceData,
58 int direction, ClientData *handlePtr));
59 static int PipeInputProc _ANSI_ARGS_((ClientData instanceData,
60 char *buf, int toRead, int *errorCode));
61 static int PipeOutputProc _ANSI_ARGS_((
62 ClientData instanceData, CONST char *buf, int toWrite,
63 int *errorCode));
64 static void PipeWatchProc _ANSI_ARGS_((ClientData instanceData, int mask));
65 static void RestoreSignals _ANSI_ARGS_((void));
66 static int SetupStdFile _ANSI_ARGS_((TclFile file, int type));
67
68 /*
69 * This structure describes the channel type structure for command pipe
70 * based IO:
71 */
72
73 static Tcl_ChannelType pipeChannelType = {
74 "pipe", /* Type name. */
75 TCL_CHANNEL_VERSION_2, /* v2 channel */
76 PipeCloseProc, /* Close proc. */
77 PipeInputProc, /* Input proc. */
78 PipeOutputProc, /* Output proc. */
79 NULL, /* Seek proc. */
80 NULL, /* Set option proc. */
81 NULL, /* Get option proc. */
82 PipeWatchProc, /* Initialize notifier. */
83 PipeGetHandleProc, /* Get OS handles out of channel. */
84 NULL, /* close2proc. */
85 PipeBlockModeProc, /* Set blocking or non-blocking mode.*/
86 NULL, /* flush proc. */
87 NULL, /* handler proc. */
88 };
89
90 /*
91 *----------------------------------------------------------------------
92 *
93 * TclpMakeFile --
94 *
95 * Make a TclFile from a channel.
96 *
97 * Results:
98 * Returns a new TclFile or NULL on failure.
99 *
100 * Side effects:
101 * None.
102 *
103 *----------------------------------------------------------------------
104 */
105
106 TclFile
107 TclpMakeFile(channel, direction)
108 Tcl_Channel channel; /* Channel to get file from. */
109 int direction; /* Either TCL_READABLE or TCL_WRITABLE. */
110 {
111 ClientData data;
112
113 if (Tcl_GetChannelHandle(channel, direction, (ClientData *) &data)
114 == TCL_OK) {
115 return MakeFile((int)data);
116 } else {
117 return (TclFile) NULL;
118 }
119 }
120
121 /*
122 *----------------------------------------------------------------------
123 *
124 * TclpOpenFile --
125 *
126 * Open a file for use in a pipeline.
127 *
128 * Results:
129 * Returns a new TclFile handle or NULL on failure.
130 *
131 * Side effects:
132 * May cause a file to be created on the file system.
133 *
134 *----------------------------------------------------------------------
135 */
136
137 TclFile
138 TclpOpenFile(fname, mode)
139 CONST char *fname; /* The name of the file to open. */
140 int mode; /* In what mode to open the file? */
141 {
142 int fd;
143 CONST char *native;
144 Tcl_DString ds;
145
146 native = Tcl_UtfToExternalDString(NULL, fname, -1, &ds);
147 fd = TclOSopen(native, mode, 0666); /* INTL: Native. */
148 Tcl_DStringFree(&ds);
149 if (fd != -1) {
150 fcntl(fd, F_SETFD, FD_CLOEXEC);
151
152 /*
153 * If the file is being opened for writing, seek to the end
154 * so we can append to any data already in the file.
155 */
156
157 if (mode & O_WRONLY) {
158 TclOSseek(fd, (Tcl_SeekOffset) 0, SEEK_END);
159 }
160
161 /*
162 * Increment the fd so it can't be 0, which would conflict with
163 * the NULL return for errors.
164 */
165
166 return MakeFile(fd);
167 }
168 return NULL;
169 }
170
171 /*
172 *----------------------------------------------------------------------
173 *
174 * TclpCreateTempFile --
175 *
176 * This function creates a temporary file initialized with an
177 * optional string, and returns a file handle with the file pointer
178 * at the beginning of the file.
179 *
180 * Results:
181 * A handle to a file.
182 *
183 * Side effects:
184 * None.
185 *
186 *----------------------------------------------------------------------
187 */
188
189 TclFile
190 TclpCreateTempFile(contents)
191 CONST char *contents; /* String to write into temp file, or NULL. */
192 {
193 char fileName[L_tmpnam + 9];
194 CONST char *native;
195 Tcl_DString dstring;
196 int fd;
197
198 /*
199 * We should also check against making more then TMP_MAX of these.
200 */
201
202 strcpy(fileName, P_tmpdir); /* INTL: Native. */
203 if (fileName[strlen(fileName) - 1] != '/') {
204 strcat(fileName, "/"); /* INTL: Native. */
205 }
206 strcat(fileName, "tclXXXXXX");
207 fd = mkstemp(fileName); /* INTL: Native. */
208 if (fd == -1) {
209 return NULL;
210 }
211 fcntl(fd, F_SETFD, FD_CLOEXEC);
212 unlink(fileName); /* INTL: Native. */
213
214 if (contents != NULL) {
215 native = Tcl_UtfToExternalDString(NULL, contents, -1, &dstring);
216 if (write(fd, native, strlen(native)) == -1) {
217 close(fd);
218 Tcl_DStringFree(&dstring);
219 return NULL;
220 }
221 Tcl_DStringFree(&dstring);
222 TclOSseek(fd, (Tcl_SeekOffset) 0, SEEK_SET);
223 }
224 return MakeFile(fd);
225 }
226
227 /*
228 *----------------------------------------------------------------------
229 *
230 * TclpTempFileName --
231 *
232 * This function returns unique filename.
233 *
234 * Results:
235 * Returns a valid Tcl_Obj* with refCount 0, or NULL on failure.
236 *
237 * Side effects:
238 * None.
239 *
240 *----------------------------------------------------------------------
241 */
242
243 Tcl_Obj*
244 TclpTempFileName()
245 {
246 char fileName[L_tmpnam + 9];
247 Tcl_Obj *result = NULL;
248 int fd;
249
250 /*
251 * We should also check against making more then TMP_MAX of these.
252 */
253
254 strcpy(fileName, P_tmpdir); /* INTL: Native. */
255 if (fileName[strlen(fileName) - 1] != '/') {
256 strcat(fileName, "/"); /* INTL: Native. */
257 }
258 strcat(fileName, "tclXXXXXX");
259 fd = mkstemp(fileName); /* INTL: Native. */
260 if (fd == -1) {
261 return NULL;
262 }
263 fcntl(fd, F_SETFD, FD_CLOEXEC);
264 unlink(fileName); /* INTL: Native. */
265
266 result = TclpNativeToNormalized((ClientData) fileName);
267 close (fd);
268 return result;
269 }
270
271 /*
272 *----------------------------------------------------------------------
273 *
274 * TclpCreatePipe --
275 *
276 * Creates a pipe - simply calls the pipe() function.
277 *
278 * Results:
279 * Returns 1 on success, 0 on failure.
280 *
281 * Side effects:
282 * Creates a pipe.
283 *
284 *----------------------------------------------------------------------
285 */
286
287 int
288 TclpCreatePipe(readPipe, writePipe)
289 TclFile *readPipe; /* Location to store file handle for
290 * read side of pipe. */
291 TclFile *writePipe; /* Location to store file handle for
292 * write side of pipe. */
293 {
294 int pipeIds[2];
295
296 if (pipe(pipeIds) != 0) {
297 return 0;
298 }
299
300 fcntl(pipeIds[0], F_SETFD, FD_CLOEXEC);
301 fcntl(pipeIds[1], F_SETFD, FD_CLOEXEC);
302
303 *readPipe = MakeFile(pipeIds[0]);
304 *writePipe = MakeFile(pipeIds[1]);
305 return 1;
306 }
307
308 /*
309 *----------------------------------------------------------------------
310 *
311 * TclpCloseFile --
312 *
313 * Implements a mechanism to close a UNIX file.
314 *
315 * Results:
316 * Returns 0 on success, or -1 on error, setting errno.
317 *
318 * Side effects:
319 * The file is closed.
320 *
321 *----------------------------------------------------------------------
322 */
323
324 int
325 TclpCloseFile(file)
326 TclFile file; /* The file to close. */
327 {
328 int fd = GetFd(file);
329
330 /*
331 * Refuse to close the fds for stdin, stdout and stderr.
332 */
333
334 if ((fd == 0) || (fd == 1) || (fd == 2)) {
335 return 0;
336 }
337
338 Tcl_DeleteFileHandler(fd);
339 return close(fd);
340 }
341
342 /*
343 *---------------------------------------------------------------------------
344 *
345 * TclpCreateProcess --
346 *
347 * Create a child process that has the specified files as its
348 * standard input, output, and error. The child process runs
349 * asynchronously and runs with the same environment variables
350 * as the creating process.
351 *
352 * The path is searched to find the specified executable.
353 *
354 * Results:
355 * The return value is TCL_ERROR and an error message is left in
356 * the interp's result if there was a problem creating the child
357 * process. Otherwise, the return value is TCL_OK and *pidPtr is
358 * filled with the process id of the child process.
359 *
360 * Side effects:
361 * A process is created.
362 *
363 *---------------------------------------------------------------------------
364 */
365
366 /* ARGSUSED */
367 int
368 TclpCreateProcess(interp, argc, argv, inputFile, outputFile, errorFile,
369 pidPtr)
370 Tcl_Interp *interp; /* Interpreter in which to leave errors that
371 * occurred when creating the child process.
372 * Error messages from the child process
373 * itself are sent to errorFile. */
374 int argc; /* Number of arguments in following array. */
375 CONST char **argv; /* Array of argument strings in UTF-8.
376 * argv[0] contains the name of the executable
377 * translated using Tcl_TranslateFileName
378 * call). Additional arguments have not been
379 * converted. */
380 TclFile inputFile; /* If non-NULL, gives the file to use as
381 * input for the child process. If inputFile
382 * file is not readable or is NULL, the child
383 * will receive no standard input. */
384 TclFile outputFile; /* If non-NULL, gives the file that
385 * receives output from the child process. If
386 * outputFile file is not writeable or is
387 * NULL, output from the child will be
388 * discarded. */
389 TclFile errorFile; /* If non-NULL, gives the file that
390 * receives errors from the child process. If
391 * errorFile file is not writeable or is NULL,
392 * errors from the child will be discarded.
393 * errorFile may be the same as outputFile. */
394 Tcl_Pid *pidPtr; /* If this procedure is successful, pidPtr
395 * is filled with the process id of the child
396 * process. */
397 {
398 TclFile errPipeIn, errPipeOut;
399 int joinThisError, count, status, fd;
400 char errSpace[200 + TCL_INTEGER_SPACE];
401 Tcl_DString *dsArray;
402 char **newArgv;
403 int pid, i;
404
405 errPipeIn = NULL;
406 errPipeOut = NULL;
407 pid = -1;
408
409 /*
410 * Create a pipe that the child can use to return error
411 * information if anything goes wrong.
412 */
413
414 if (TclpCreatePipe(&errPipeIn, &errPipeOut) == 0) {
415 Tcl_AppendResult(interp, "couldn't create pipe: ",
416 Tcl_PosixError(interp), (char *) NULL);
417 goto error;
418 }
419
420 /*
421 * We need to allocate and convert this before the fork
422 * so it is properly deallocated later
423 */
424 dsArray = (Tcl_DString *) ckalloc(argc * sizeof(Tcl_DString));
425 newArgv = (char **) ckalloc((argc+1) * sizeof(char *));
426 newArgv[argc] = NULL;
427 for (i = 0; i < argc; i++) {
428 newArgv[i] = Tcl_UtfToExternalDString(NULL, argv[i], -1, &dsArray[i]);
429 }
430
431 joinThisError = errorFile && (errorFile == outputFile);
432 pid = fork();
433 if (pid == 0) {
434 fd = GetFd(errPipeOut);
435
436 /*
437 * Set up stdio file handles for the child process.
438 */
439
440 if (!SetupStdFile(inputFile, TCL_STDIN)
441 || !SetupStdFile(outputFile, TCL_STDOUT)
442 || (!joinThisError && !SetupStdFile(errorFile, TCL_STDERR))
443 || (joinThisError &&
444 ((dup2(1,2) == -1) ||
445 (fcntl(2, F_SETFD, 0) != 0)))) {
446 sprintf(errSpace,
447 "%dforked process couldn't set up input/output: ", errno);
448 write(fd, errSpace, (size_t) strlen(errSpace));
449 _exit(1);
450 }
451
452 /*
453 * Close the input side of the error pipe.
454 */
455
456 RestoreSignals();
457 execvp(newArgv[0], newArgv); /* INTL: Native. */
458 sprintf(errSpace, "%dcouldn't execute \"%.150s\": ", errno, argv[0]);
459 write(fd, errSpace, (size_t) strlen(errSpace));
460 _exit(1);
461 }
462
463 /*
464 * Free the mem we used for the fork
465 */
466 for (i = 0; i < argc; i++) {
467 Tcl_DStringFree(&dsArray[i]);
468 }
469 ckfree((char *) dsArray);
470 ckfree((char *) newArgv);
471
472 if (pid == -1) {
473 Tcl_AppendResult(interp, "couldn't fork child process: ",
474 Tcl_PosixError(interp), (char *) NULL);
475 goto error;
476 }
477
478 /*
479 * Read back from the error pipe to see if the child started
480 * up OK. The info in the pipe (if any) consists of a decimal
481 * errno value followed by an error message.
482 */
483
484 TclpCloseFile(errPipeOut);
485 errPipeOut = NULL;
486
487 fd = GetFd(errPipeIn);
488 count = read(fd, errSpace, (size_t) (sizeof(errSpace) - 1));
489 if (count > 0) {
490 char *end;
491 errSpace[count] = 0;
492 errno = strtol(errSpace, &end, 10);
493 Tcl_AppendResult(interp, end, Tcl_PosixError(interp),
494 (char *) NULL);
495 goto error;
496 }
497
498 TclpCloseFile(errPipeIn);
499 *pidPtr = (Tcl_Pid) pid;
500 return TCL_OK;
501
502 error:
503 if (pid != -1) {
504 /*
505 * Reap the child process now if an error occurred during its
506 * startup. We don't call this with WNOHANG because that can lead to
507 * defunct processes on an MP system. We shouldn't have to worry
508 * about hanging here, since this is the error case. [Bug: 6148]
509 */
510
511 Tcl_WaitPid((Tcl_Pid) pid, &status, 0);
512 }
513
514 if (errPipeIn) {
515 TclpCloseFile(errPipeIn);
516 }
517 if (errPipeOut) {
518 TclpCloseFile(errPipeOut);
519 }
520 return TCL_ERROR;
521 }
522
523 /*
524 *----------------------------------------------------------------------
525 *
526 * RestoreSignals --
527 *
528 * This procedure is invoked in a forked child process just before
529 * exec-ing a new program to restore all signals to their default
530 * settings.
531 *
532 * Results:
533 * None.
534 *
535 * Side effects:
536 * Signal settings get changed.
537 *
538 *----------------------------------------------------------------------
539 */
540
541 static void
542 RestoreSignals()
543 {
544 #ifdef SIGABRT
545 signal(SIGABRT, SIG_DFL);
546 #endif
547 #ifdef SIGALRM
548 signal(SIGALRM, SIG_DFL);
549 #endif
550 #ifdef SIGFPE
551 signal(SIGFPE, SIG_DFL);
552 #endif
553 #ifdef SIGHUP
554 signal(SIGHUP, SIG_DFL);
555 #endif
556 #ifdef SIGILL
557 signal(SIGILL, SIG_DFL);
558 #endif
559 #ifdef SIGINT
560 signal(SIGINT, SIG_DFL);
561 #endif
562 #ifdef SIGPIPE
563 signal(SIGPIPE, SIG_DFL);
564 #endif
565 #ifdef SIGQUIT
566 signal(SIGQUIT, SIG_DFL);
567 #endif
568 #ifdef SIGSEGV
569 signal(SIGSEGV, SIG_DFL);
570 #endif
571 #ifdef SIGTERM
572 signal(SIGTERM, SIG_DFL);
573 #endif
574 #ifdef SIGUSR1
575 signal(SIGUSR1, SIG_DFL);
576 #endif
577 #ifdef SIGUSR2
578 signal(SIGUSR2, SIG_DFL);
579 #endif
580 #ifdef SIGCHLD
581 signal(SIGCHLD, SIG_DFL);
582 #endif
583 #ifdef SIGCONT
584 signal(SIGCONT, SIG_DFL);
585 #endif
586 #ifdef SIGTSTP
587 signal(SIGTSTP, SIG_DFL);
588 #endif
589 #ifdef SIGTTIN
590 signal(SIGTTIN, SIG_DFL);
591 #endif
592 #ifdef SIGTTOU
593 signal(SIGTTOU, SIG_DFL);
594 #endif
595 }
596
597 /*
598 *----------------------------------------------------------------------
599 *
600 * SetupStdFile --
601 *
602 * Set up stdio file handles for the child process, using the
603 * current standard channels if no other files are specified.
604 * If no standard channel is defined, or if no file is associated
605 * with the channel, then the corresponding standard fd is closed.
606 *
607 * Results:
608 * Returns 1 on success, or 0 on failure.
609 *
610 * Side effects:
611 * Replaces stdio fds.
612 *
613 *----------------------------------------------------------------------
614 */
615
616 static int
617 SetupStdFile(file, type)
618 TclFile file; /* File to dup, or NULL. */
619 int type; /* One of TCL_STDIN, TCL_STDOUT, TCL_STDERR */
620 {
621 Tcl_Channel channel;
622 int fd;
623 int targetFd = 0; /* Initializations here needed only to */
624 int direction = 0; /* prevent warnings about using uninitialized
625 * variables. */
626
627 switch (type) {
628 case TCL_STDIN:
629 targetFd = 0;
630 direction = TCL_READABLE;
631 break;
632 case TCL_STDOUT:
633 targetFd = 1;
634 direction = TCL_WRITABLE;
635 break;
636 case TCL_STDERR:
637 targetFd = 2;
638 direction = TCL_WRITABLE;
639 break;
640 }
641
642 if (!file) {
643 channel = Tcl_GetStdChannel(type);
644 if (channel) {
645 file = TclpMakeFile(channel, direction);
646 }
647 }
648 if (file) {
649 fd = GetFd(file);
650 if (fd != targetFd) {
651 if (dup2(fd, targetFd) == -1) {
652 return 0;
653 }
654
655 /*
656 * Must clear the close-on-exec flag for the target FD, since
657 * some systems (e.g. Ultrix) do not clear the CLOEXEC flag on
658 * the target FD.
659 */
660
661 fcntl(targetFd, F_SETFD, 0);
662 } else {
663 int result;
664
665 /*
666 * Since we aren't dup'ing the file, we need to explicitly clear
667 * the close-on-exec flag.
668 */
669
670 result = fcntl(fd, F_SETFD, 0);
671 }
672 } else {
673 close(targetFd);
674 }
675 return 1;
676 }
677
678 /*
679 *----------------------------------------------------------------------
680 *
681 * TclpCreateCommandChannel --
682 *
683 * This function is called by the generic IO level to perform
684 * the platform specific channel initialization for a command
685 * channel.
686 *
687 * Results:
688 * Returns a new channel or NULL on failure.
689 *
690 * Side effects:
691 * Allocates a new channel.
692 *
693 *----------------------------------------------------------------------
694 */
695
696 Tcl_Channel
697 TclpCreateCommandChannel(readFile, writeFile, errorFile, numPids, pidPtr)
698 TclFile readFile; /* If non-null, gives the file for reading. */
699 TclFile writeFile; /* If non-null, gives the file for writing. */
700 TclFile errorFile; /* If non-null, gives the file where errors
701 * can be read. */
702 int numPids; /* The number of pids in the pid array. */
703 Tcl_Pid *pidPtr; /* An array of process identifiers.
704 * Allocated by the caller, freed when
705 * the channel is closed or the processes
706 * are detached (in a background exec). */
707 {
708 char channelName[16 + TCL_INTEGER_SPACE];
709 int channelId;
710 PipeState *statePtr = (PipeState *) ckalloc((unsigned) sizeof(PipeState));
711 int mode;
712
713 statePtr->inFile = readFile;
714 statePtr->outFile = writeFile;
715 statePtr->errorFile = errorFile;
716 statePtr->numPids = numPids;
717 statePtr->pidPtr = pidPtr;
718 statePtr->isNonBlocking = 0;
719
720 mode = 0;
721 if (readFile) {
722 mode |= TCL_READABLE;
723 }
724 if (writeFile) {
725 mode |= TCL_WRITABLE;
726 }
727
728 /*
729 * Use one of the fds associated with the channel as the
730 * channel id.
731 */
732
733 if (readFile) {
734 channelId = GetFd(readFile);
735 } else if (writeFile) {
736 channelId = GetFd(writeFile);
737 } else if (errorFile) {
738 channelId = GetFd(errorFile);
739 } else {
740 channelId = 0;
741 }
742
743 /*
744 * For backward compatibility with previous versions of Tcl, we
745 * use "file%d" as the base name for pipes even though it would
746 * be more natural to use "pipe%d".
747 */
748
749 sprintf(channelName, "file%d", channelId);
750 statePtr->channel = Tcl_CreateChannel(&pipeChannelType, channelName,
751 (ClientData) statePtr, mode);
752 return statePtr->channel;
753 }
754
755 /*
756 *----------------------------------------------------------------------
757 *
758 * TclGetAndDetachPids --
759 *
760 * This procedure is invoked in the generic implementation of a
761 * background "exec" (An exec when invoked with a terminating "&")
762 * to store a list of the PIDs for processes in a command pipeline
763 * in the interp's result and to detach the processes.
764 *
765 * Results:
766 * None.
767 *
768 * Side effects:
769 * Modifies the interp's result. Detaches processes.
770 *
771 *----------------------------------------------------------------------
772 */
773
774 void
775 TclGetAndDetachPids(interp, chan)
776 Tcl_Interp *interp;
777 Tcl_Channel chan;
778 {
779 PipeState *pipePtr;
780 Tcl_ChannelType *chanTypePtr;
781 int i;
782 char buf[TCL_INTEGER_SPACE];
783
784 /*
785 * Punt if the channel is not a command channel.
786 */
787
788 chanTypePtr = Tcl_GetChannelType(chan);
789 if (chanTypePtr != &pipeChannelType) {
790 return;
791 }
792
793 pipePtr = (PipeState *) Tcl_GetChannelInstanceData(chan);
794 for (i = 0; i < pipePtr->numPids; i++) {
795 TclFormatInt(buf, (long) TclpGetPid(pipePtr->pidPtr[i]));
796 Tcl_AppendElement(interp, buf);
797 Tcl_DetachPids(1, &(pipePtr->pidPtr[i]));
798 }
799 if (pipePtr->numPids > 0) {
800 ckfree((char *) pipePtr->pidPtr);
801 pipePtr->numPids = 0;
802 }
803 }
804
805 /*
806 *----------------------------------------------------------------------
807 *
808 * PipeBlockModeProc --
809 *
810 * Helper procedure to set blocking and nonblocking modes on a
811 * pipe based channel. Invoked by generic IO level code.
812 *
813 * Results:
814 * 0 if successful, errno when failed.
815 *
816 * Side effects:
817 * Sets the device into blocking or non-blocking mode.
818 *
819 *----------------------------------------------------------------------
820 */
821
822 /* ARGSUSED */
823 static int
824 PipeBlockModeProc(instanceData, mode)
825 ClientData instanceData; /* Pipe state. */
826 int mode; /* The mode to set. Can be one of
827 * TCL_MODE_BLOCKING or
828 * TCL_MODE_NONBLOCKING. */
829 {
830 PipeState *psPtr = (PipeState *) instanceData;
831 int curStatus;
832 int fd;
833
834 #ifndef USE_FIONBIO
835 if (psPtr->inFile) {
836 fd = GetFd(psPtr->inFile);
837 curStatus = fcntl(fd, F_GETFL);
838 if (mode == TCL_MODE_BLOCKING) {
839 curStatus &= (~(O_NONBLOCK));
840 } else {
841 curStatus |= O_NONBLOCK;
842 }
843 if (fcntl(fd, F_SETFL, curStatus) < 0) {
844 return errno;
845 }
846 }
847 if (psPtr->outFile) {
848 fd = GetFd(psPtr->outFile);
849 curStatus = fcntl(fd, F_GETFL);
850 if (mode == TCL_MODE_BLOCKING) {
851 curStatus &= (~(O_NONBLOCK));
852 } else {
853 curStatus |= O_NONBLOCK;
854 }
855 if (fcntl(fd, F_SETFL, curStatus) < 0) {
856 return errno;
857 }
858 }
859 #endif /* !FIONBIO */
860
861 #ifdef USE_FIONBIO
862 if (psPtr->inFile) {
863 fd = GetFd(psPtr->inFile);
864 if (mode == TCL_MODE_BLOCKING) {
865 curStatus = 0;
866 } else {
867 curStatus = 1;
868 }
869 if (ioctl(fd, (int) FIONBIO, &curStatus) < 0) {
870 return errno;
871 }
872 }
873 if (psPtr->outFile != NULL) {
874 fd = GetFd(psPtr->outFile);
875 if (mode == TCL_MODE_BLOCKING) {
876 curStatus = 0;
877 } else {
878 curStatus = 1;
879 }
880 if (ioctl(fd, (int) FIONBIO, &curStatus) < 0) {
881 return errno;
882 }
883 }
884 #endif /* USE_FIONBIO */
885
886 psPtr->isNonBlocking = (mode == TCL_MODE_NONBLOCKING);
887
888 return 0;
889 }
890
891 /*
892 *----------------------------------------------------------------------
893 *
894 * PipeCloseProc --
895 *
896 * This procedure is invoked by the generic IO level to perform
897 * channel-type-specific cleanup when a command pipeline channel
898 * is closed.
899 *
900 * Results:
901 * 0 on success, errno otherwise.
902 *
903 * Side effects:
904 * Closes the command pipeline channel.
905 *
906 *----------------------------------------------------------------------
907 */
908
909 /* ARGSUSED */
910 static int
911 PipeCloseProc(instanceData, interp)
912 ClientData instanceData; /* The pipe to close. */
913 Tcl_Interp *interp; /* For error reporting. */
914 {
915 PipeState *pipePtr;
916 Tcl_Channel errChan;
917 int errorCode, result;
918
919 errorCode = 0;
920 result = 0;
921 pipePtr = (PipeState *) instanceData;
922 if (pipePtr->inFile) {
923 if (TclpCloseFile(pipePtr->inFile) < 0) {
924 errorCode = errno;
925 }
926 }
927 if (pipePtr->outFile) {
928 if ((TclpCloseFile(pipePtr->outFile) < 0) && (errorCode == 0)) {
929 errorCode = errno;
930 }
931 }
932
933 if (pipePtr->isNonBlocking || TclInExit()) {
934
935 /*
936 * If the channel is non-blocking or Tcl is being cleaned up, just
937 * detach the children PIDs, reap them (important if we are in a
938 * dynamic load module), and discard the errorFile.
939 */
940
941 Tcl_DetachPids(pipePtr->numPids, pipePtr->pidPtr);
942 Tcl_ReapDetachedProcs();
943
944 if (pipePtr->errorFile) {
945 TclpCloseFile(pipePtr->errorFile);
946 }
947 } else {
948
949 /*
950 * Wrap the error file into a channel and give it to the cleanup
951 * routine.
952 */
953
954 if (pipePtr->errorFile) {
955 errChan = Tcl_MakeFileChannel(
956 (ClientData) GetFd(pipePtr->errorFile), TCL_READABLE);
957 } else {
958 errChan = NULL;
959 }
960 result = TclCleanupChildren(interp, pipePtr->numPids, pipePtr->pidPtr,
961 errChan);
962 }
963
964 if (pipePtr->numPids != 0) {
965 ckfree((char *) pipePtr->pidPtr);
966 }
967 ckfree((char *) pipePtr);
968 if (errorCode == 0) {
969 return result;
970 }
971 return errorCode;
972 }
973
974 /*
975 *----------------------------------------------------------------------
976 *
977 * PipeInputProc --
978 *
979 * This procedure is invoked from the generic IO level to read
980 * input from a command pipeline based channel.
981 *
982 * Results:
983 * The number of bytes read is returned or -1 on error. An output
984 * argument contains a POSIX error code if an error occurs, or zero.
985 *
986 * Side effects:
987 * Reads input from the input device of the channel.
988 *
989 *----------------------------------------------------------------------
990 */
991
992 static int
993 PipeInputProc(instanceData, buf, toRead, errorCodePtr)
994 ClientData instanceData; /* Pipe state. */
995 char *buf; /* Where to store data read. */
996 int toRead; /* How much space is available
997 * in the buffer? */
998 int *errorCodePtr; /* Where to store error code. */
999 {
1000 PipeState *psPtr = (PipeState *) instanceData;
1001 int bytesRead; /* How many bytes were actually
1002 * read from the input device? */
1003
1004 *errorCodePtr = 0;
1005
1006 /*
1007 * Assume there is always enough input available. This will block
1008 * appropriately, and read will unblock as soon as a short read is
1009 * possible, if the channel is in blocking mode. If the channel is
1010 * nonblocking, the read will never block.
1011 * Some OSes can throw an interrupt error, for which we should
1012 * immediately retry. [Bug #415131]
1013 */
1014
1015 do {
1016 bytesRead = read (GetFd(psPtr->inFile), buf, (size_t) toRead);
1017 } while ((bytesRead < 0) && (errno == EINTR));
1018
1019 if (bytesRead < 0) {
1020 *errorCodePtr = errno;
1021 return -1;
1022 } else {
1023 return bytesRead;
1024 }
1025 }
1026
1027 /*
1028 *----------------------------------------------------------------------
1029 *
1030 * PipeOutputProc--
1031 *
1032 * This procedure is invoked from the generic IO level to write
1033 * output to a command pipeline based channel.
1034 *
1035 * Results:
1036 * The number of bytes written is returned or -1 on error. An
1037 * output argument contains a POSIX error code if an error occurred,
1038 * or zero.
1039 *
1040 * Side effects:
1041 * Writes output on the output device of the channel.
1042 *
1043 *----------------------------------------------------------------------
1044 */
1045
1046 static int
1047 PipeOutputProc(instanceData, buf, toWrite, errorCodePtr)
1048 ClientData instanceData; /* Pipe state. */
1049 CONST char *buf; /* The data buffer. */
1050 int toWrite; /* How many bytes to write? */
1051 int *errorCodePtr; /* Where to store error code. */
1052 {
1053 PipeState *psPtr = (PipeState *) instanceData;
1054 int written;
1055
1056 *errorCodePtr = 0;
1057
1058 /*
1059 * Some OSes can throw an interrupt error, for which we should
1060 * immediately retry. [Bug #415131]
1061 */
1062
1063 do {
1064 written = write(GetFd(psPtr->outFile), buf, (size_t) toWrite);
1065 } while ((written < 0) && (errno == EINTR));
1066
1067 if (written < 0) {
1068 *errorCodePtr = errno;
1069 return -1;
1070 } else {
1071 return written;
1072 }
1073 }
1074
1075 /*
1076 *----------------------------------------------------------------------
1077 *
1078 * PipeWatchProc --
1079 *
1080 * Initialize the notifier to watch the fds from this channel.
1081 *
1082 * Results:
1083 * None.
1084 *
1085 * Side effects:
1086 * Sets up the notifier so that a future event on the channel will
1087 * be seen by Tcl.
1088 *
1089 *----------------------------------------------------------------------
1090 */
1091
1092 static void
1093 PipeWatchProc(instanceData, mask)
1094 ClientData instanceData; /* The pipe state. */
1095 int mask; /* Events of interest; an OR-ed
1096 * combination of TCL_READABLE,
1097 * TCL_WRITABEL and TCL_EXCEPTION. */
1098 {
1099 PipeState *psPtr = (PipeState *) instanceData;
1100 int newmask;
1101
1102 if (psPtr->inFile) {
1103 newmask = mask & (TCL_READABLE | TCL_EXCEPTION);
1104 if (newmask) {
1105 Tcl_CreateFileHandler(GetFd(psPtr->inFile), mask,
1106 (Tcl_FileProc *) Tcl_NotifyChannel,
1107 (ClientData) psPtr->channel);
1108 } else {
1109 Tcl_DeleteFileHandler(GetFd(psPtr->inFile));
1110 }
1111 }
1112 if (psPtr->outFile) {
1113 newmask = mask & (TCL_WRITABLE | TCL_EXCEPTION);
1114 if (newmask) {
1115 Tcl_CreateFileHandler(GetFd(psPtr->outFile), mask,
1116 (Tcl_FileProc *) Tcl_NotifyChannel,
1117 (ClientData) psPtr->channel);
1118 } else {
1119 Tcl_DeleteFileHandler(GetFd(psPtr->outFile));
1120 }
1121 }
1122 }
1123
1124 /*
1125 *----------------------------------------------------------------------
1126 *
1127 * PipeGetHandleProc --
1128 *
1129 * Called from Tcl_GetChannelHandle to retrieve OS handles from
1130 * inside a command pipeline based channel.
1131 *
1132 * Results:
1133 * Returns TCL_OK with the fd in handlePtr, or TCL_ERROR if
1134 * there is no handle for the specified direction.
1135 *
1136 * Side effects:
1137 * None.
1138 *
1139 *----------------------------------------------------------------------
1140 */
1141
1142 static int
1143 PipeGetHandleProc(instanceData, direction, handlePtr)
1144 ClientData instanceData; /* The pipe state. */
1145 int direction; /* TCL_READABLE or TCL_WRITABLE */
1146 ClientData *handlePtr; /* Where to store the handle. */
1147 {
1148 PipeState *psPtr = (PipeState *) instanceData;
1149
1150 if (direction == TCL_READABLE && psPtr->inFile) {
1151 *handlePtr = (ClientData) GetFd(psPtr->inFile);
1152 return TCL_OK;
1153 }
1154 if (direction == TCL_WRITABLE && psPtr->outFile) {
1155 *handlePtr = (ClientData) GetFd(psPtr->outFile);
1156 return TCL_OK;
1157 }
1158 return TCL_ERROR;
1159 }
1160
1161 /*
1162 *----------------------------------------------------------------------
1163 *
1164 * Tcl_WaitPid --
1165 *
1166 * Implements the waitpid system call on Unix systems.
1167 *
1168 * Results:
1169 * Result of calling waitpid.
1170 *
1171 * Side effects:
1172 * Waits for a process to terminate.
1173 *
1174 *----------------------------------------------------------------------
1175 */
1176
1177 Tcl_Pid
1178 Tcl_WaitPid(pid, statPtr, options)
1179 Tcl_Pid pid;
1180 int *statPtr;
1181 int options;
1182 {
1183 int result;
1184 pid_t real_pid;
1185
1186 real_pid = (pid_t) pid;
1187 while (1) {
1188 result = (int) waitpid(real_pid, statPtr, options);
1189 if ((result != -1) || (errno != EINTR)) {
1190 return (Tcl_Pid) result;
1191 }
1192 }
1193 }
1194
1195 /*
1196 *----------------------------------------------------------------------
1197 *
1198 * Tcl_PidObjCmd --
1199 *
1200 * This procedure is invoked to process the "pid" Tcl command.
1201 * See the user documentation for details on what it does.
1202 *
1203 * Results:
1204 * A standard Tcl result.
1205 *
1206 * Side effects:
1207 * See the user documentation.
1208 *
1209 *----------------------------------------------------------------------
1210 */
1211
1212 /* ARGSUSED */
1213 int
1214 Tcl_PidObjCmd(dummy, interp, objc, objv)
1215 ClientData dummy; /* Not used. */
1216 Tcl_Interp *interp; /* Current interpreter. */
1217 int objc; /* Number of arguments. */
1218 Tcl_Obj *CONST *objv; /* Argument strings. */
1219 {
1220 Tcl_Channel chan;
1221 Tcl_ChannelType *chanTypePtr;
1222 PipeState *pipePtr;
1223 int i;
1224 Tcl_Obj *resultPtr, *longObjPtr;
1225
1226 if (objc > 2) {
1227 Tcl_WrongNumArgs(interp, 1, objv, "?channelId?");
1228 return TCL_ERROR;
1229 }
1230 if (objc == 1) {
1231 Tcl_SetLongObj(Tcl_GetObjResult(interp), (long) getpid());
1232 } else {
1233 chan = Tcl_GetChannel(interp, Tcl_GetString(objv[1]), NULL);
1234 if (chan == (Tcl_Channel) NULL) {
1235 return TCL_ERROR;
1236 }
1237 chanTypePtr = Tcl_GetChannelType(chan);
1238 if (chanTypePtr != &pipeChannelType) {
1239 return TCL_OK;
1240 }
1241 pipePtr = (PipeState *) Tcl_GetChannelInstanceData(chan);
1242 resultPtr = Tcl_GetObjResult(interp);
1243 for (i = 0; i < pipePtr->numPids; i++) {
1244 longObjPtr = Tcl_NewLongObj((long) TclpGetPid(pipePtr->pidPtr[i]));
1245 Tcl_ListObjAppendElement(NULL, resultPtr, longObjPtr);
1246 }
1247 }
1248 return TCL_OK;
1249 }