Debian Codegraph @

unix/tclUnixPipe.c

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