a4bfbf1f457b6fe3b40e1a915aa5a8afa32565c2
[sbcl.git] / src / runtime / run-program.c
1 /*
2  * support for the Lisp function RUN-PROGRAM and friends
3  */
4
5 /*
6  * This software is part of the SBCL system. See the README file for
7  * more information.
8  *
9  * This software is derived from the CMU CL system, which was
10  * written at Carnegie Mellon University and released into the
11  * public domain. The software is in the public domain and is
12  * provided with absolutely no warranty. See the COPYING and CREDITS
13  * files for more information.
14  */
15
16 /*
17  * $Header$
18  */
19
20 #include <sys/file.h>
21 #include <sys/fcntl.h>
22 #include <sys/ioctl.h>
23 #ifdef SVR4
24 #include <unistd.h>
25 #endif
26
27 int spawn(char *program, char *argv[], char *envp[], char *pty_name,
28           int stdin, int stdout, int stderr)
29 {
30     int pid = fork();
31     int fd;
32
33     if (pid != 0)
34         return pid;
35
36     /* Put us in our own process group. */
37 #if defined(hpux)
38     setsid();
39 #elif defined(SVR4)
40     setpgrp();
41 #else
42     setpgrp(0, getpid());
43 #endif
44
45     /* If we are supposed to be part of some other pty, go for it. */
46     if (pty_name) {
47 #if !defined(hpux) && !defined(SVR4)
48         fd = open("/dev/tty", O_RDWR, 0);
49         if (fd >= 0) {
50             ioctl(fd, TIOCNOTTY, 0);
51             close(fd);
52         }
53 #endif
54
55         fd = open(pty_name, O_RDWR, 0);
56         dup2(fd, 0);
57         dup2(fd, 1);
58         dup2(fd, 2);
59         close(fd);
60     }
61
62     /* Set up stdin, stdout, and stderr */
63     if (stdin >= 0)
64         dup2(stdin, 0);
65     if (stdout >= 0)
66         dup2(stdout, 1);
67     if (stderr >= 0)
68         dup2(stderr, 2);
69
70     /* Close all other fds. */
71 #ifdef SVR4
72     for (fd = sysconf(_SC_OPEN_MAX)-1; fd >= 3; fd--)
73         close(fd);
74 #else
75     for (fd = getdtablesize()-1; fd >= 3; fd--)
76         close(fd);
77 #endif
78
79     /* Exec the program. */
80     execve(program, argv, envp);
81
82     /* It didn't work, so try /bin/sh. */
83     argv[0] = program;
84     argv[-1] = "sh";
85     execve("/bin/sh", argv-1, envp);
86
87     /* The exec didn't work, flame out. */
88     exit(1);
89 }