0.7.2.6:
[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 #include <stdlib.h>
17 #include <sys/file.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <sys/ioctl.h>
22 #if defined(SVR4) || defined(__linux__)
23 #include <unistd.h>
24 #endif
25
26 int spawn(char *program, char *argv[], char *envp[], char *pty_name,
27           int stdin, int stdout, int stderr)
28 {
29     int pid = fork();
30     int fd;
31
32     if (pid != 0)
33         return pid;
34
35     /* Put us in our own process group. */
36 #if defined(hpux)
37     setsid();
38 #elif defined(SVR4) || defined(__linux__)
39     setpgrp();
40 #else
41     setpgrp(0, getpid());
42 #endif
43
44     /* If we are supposed to be part of some other pty, go for it. */
45     if (pty_name) {
46 #if !defined(hpux) && !defined(SVR4)
47         fd = open("/dev/tty", O_RDWR, 0);
48         if (fd >= 0) {
49             ioctl(fd, TIOCNOTTY, 0);
50             close(fd);
51         }
52 #endif
53
54         fd = open(pty_name, O_RDWR, 0);
55         dup2(fd, 0);
56         dup2(fd, 1);
57         dup2(fd, 2);
58         close(fd);
59     }
60
61     /* Set up stdin, stdout, and stderr */
62     if (stdin >= 0)
63         dup2(stdin, 0);
64     if (stdout >= 0)
65         dup2(stdout, 1);
66     if (stderr >= 0)
67         dup2(stderr, 2);
68
69     /* Close all other fds. */
70 #ifdef SVR4
71     for (fd = sysconf(_SC_OPEN_MAX)-1; fd >= 3; fd--)
72         close(fd);
73 #else
74     for (fd = getdtablesize()-1; fd >= 3; fd--)
75         close(fd);
76 #endif
77
78     /* Exec the program. */
79     execve(program, argv, envp);
80
81     /* It didn't work, so try /bin/sh. */
82     argv[0] = program;
83     argv[-1] = "sh";
84     execve("/bin/sh", argv-1, envp);
85
86     /* The exec didn't work, flame out. */
87     exit(1);
88 }