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