0.7.1.15:
[sbcl.git] / src / code / run-program.lisp
1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
2 ;;;; from inside SBCL
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB-IMPL") ;(SB-IMPL, not SB!IMPL, since we're built in warm load.)
14 \f
15 ;;;; hacking the Unix environment
16 ;;;;
17 ;;;; In the original CMU CL code that LOAD-FOREIGN is derived from, the
18 ;;;; Unix environment (as in "man environ") was represented as an
19 ;;;; alist from keywords to strings, so that e.g. the Unix environment
20 ;;;;   "SHELL=/bin/bash" "HOME=/root" "PAGER=less"
21 ;;;; was represented as
22 ;;;;   ((:SHELL . "/bin/bash") (:HOME . "/root") (:PAGER "less"))
23 ;;;; This had a few problems in principle: the mapping into
24 ;;;; keyword symbols smashed the case of environment
25 ;;;; variables, and the whole mapping depended on the presence of
26 ;;;; #\= characters in the environment strings. In practice these
27 ;;;; problems weren't hugely important, since conventionally environment
28 ;;;; variables are uppercase strings followed by #\= followed by
29 ;;;; arbitrary data. However, since it's so manifestly not The Right
30 ;;;; Thing to make code which breaks unnecessarily on input which
31 ;;;; doesn't follow what is, after all, only a tradition, we've switched
32 ;;;; formats in SBCL, so that the fundamental environment list
33 ;;;; is just a list of strings, with a one-to-one-correspondence
34 ;;;; to the C-level representation. I.e., in the example above,
35 ;;;; the SBCL representation is
36 ;;;;   '("SHELL=/bin/bash" "HOME=/root" "PAGER=less")
37 ;;;; CMU CL's implementation is currently supported to help with porting.
38 ;;;;
39 ;;;; It's not obvious that this code belongs here (instead of e.g. in
40 ;;;; unix.lisp), since it has only a weak logical connection with
41 ;;;; RUN-PROGRAM. However, physically it's convenient to put it here.
42 ;;;; It's not needed at cold init, so we *can* put it in this
43 ;;;; warm-loaded file. And by putting it in this warm-loaded file, we
44 ;;;; make it easy for it to get to the C-level 'environ' variable.
45 ;;;; which (at least in sbcl-0.6.10 on Red Hat Linux 6.2) is not
46 ;;;; visible at GENESIS time.
47
48 (define-alien-routine wrapped-environ (* c-string))
49 (defun posix-environ ()
50   "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
51   (c-strings->string-list (wrapped-environ)))
52
53 ;;; Convert as best we can from an SBCL representation of a Unix
54 ;;; environment to a CMU CL representation.
55 ;;;
56 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
57 ;;; WARNING:
58 ;;;   smashing case of "Bletch=fub" in conversion to CMU-CL-style
59 ;;;     environment alist
60 ;;; WARNING:
61 ;;;   no #\= in "Noggin", eliding it in CMU-CL-style environment alist
62 ;;; ((:BLETCH . "fub") (:YES . "No!"))
63 (defun unix-environment-cmucl-from-sbcl (sbcl)
64   (mapcan
65    (lambda (string)
66      (declare (type simple-string string))
67      (let ((=-pos (position #\= string :test #'equal)))
68        (if =-pos
69            (list
70             (let* ((key-as-string (subseq string 0 =-pos))
71                    (key-as-upcase-string (string-upcase key-as-string))
72                    (key (keywordicate key-as-upcase-string))
73                    (val (subseq string (1+ =-pos))))
74               (unless (string= key-as-string key-as-upcase-string)
75                 (warn "smashing case of ~S in conversion to CMU-CL-style ~
76                       environment alist"
77                       string))
78               (cons key val)))
79            (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
80                  string))))
81    sbcl))
82
83 ;;; Convert from a CMU CL representation of a Unix environment to a
84 ;;; SBCL representation.
85 (defun unix-environment-sbcl-from-cmucl (cmucl)
86   (mapcar
87    (lambda (cons)
88      (destructuring-bind (key . val) cons
89        (declare (type keyword key) (type simple-string val))
90        (concatenate 'simple-string (symbol-name key) "=" val)))
91    cmucl))
92 \f
93 ;;;; Import wait3(2) from Unix.
94
95 (define-alien-routine ("wait3" c-wait3) sb-alien:int
96   (status sb-alien:int :out)
97   (options sb-alien:int)
98   (rusage sb-alien:int))
99
100 (defconstant wait-wnohang #-svr4 1 #+svr4 #o100)
101 (defconstant wait-wuntraced #-svr4 2 #+svr4 4)
102 (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced)
103
104 (defun wait3 (&optional do-not-hang check-for-stopped)
105   "Return any available status information on child process. "
106   (multiple-value-bind (pid status)
107       (c-wait3 (logior (if do-not-hang
108                            wait-wnohang
109                            0)
110                        (if check-for-stopped
111                            wait-wuntraced
112                            0))
113                0)
114     (cond ((or (minusp pid)
115                (zerop pid))
116            nil)
117           ((eql (ldb (byte 8 0) status)
118                 wait-wstopped)
119            (values pid
120                    :stopped
121                    (ldb (byte 8 8) status)))
122           ((zerop (ldb (byte 7 0) status))
123            (values pid
124                    :exited
125                    (ldb (byte 8 8) status)))
126           (t
127            (let ((signal (ldb (byte 7 0) status)))
128              (values pid
129                      (if (position signal
130                                    #.(vector
131                                       (sb-unix:unix-signal-number :sigstop)
132                                       (sb-unix:unix-signal-number :sigtstp)
133                                       (sb-unix:unix-signal-number :sigttin)
134                                       (sb-unix:unix-signal-number :sigttou)))
135                          :stopped
136                          :signaled)
137                      signal
138                      (not (zerop (ldb (byte 1 7) status)))))))))
139 \f
140 ;;;; process control stuff
141
142 (defvar *active-processes* nil
143   "List of process structures for all active processes.")
144
145 (defstruct (process (:copier nil))
146   pid                 ; PID of child process
147   %status             ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
148   exit-code           ; either exit code or signal
149   core-dumped         ; T if a core image was dumped
150   pty                 ; stream to child's pty, or NIL
151   input               ; stream to child's input, or NIL
152   output              ; stream from child's output, or NIL
153   error               ; stream from child's error output, or NIL
154   status-hook         ; closure to call when PROC changes status
155   plist               ; a place for clients to stash things
156   cookie)             ; list of the number of pipes from the subproc
157
158 (defmethod print-object ((process process) stream)
159   (print-unreadable-object (process stream :type t)
160     (format stream
161             "~W ~S"
162             (process-pid process)
163             (process-status process)))
164   process)
165
166 (defun process-status (proc)
167   "Return the current status of process.  The result is one of :RUNNING,
168    :STOPPED, :EXITED, or :SIGNALED."
169   (get-processes-status-changes)
170   (process-%status proc))
171
172 (defun process-wait (proc &optional check-for-stopped)
173   "Wait for PROC to quit running for some reason.  Returns PROC."
174   (loop
175       (case (process-status proc)
176         (:running)
177         (:stopped
178          (when check-for-stopped
179            (return)))
180         (t
181          (when (zerop (car (process-cookie proc)))
182            (return))))
183       (sb-sys:serve-all-events 1))
184   proc)
185
186 #-hpux
187 ;;; Find the current foreground process group id.
188 (defun find-current-foreground-process (proc)
189   (with-alien ((result sb-alien:int))
190     (multiple-value-bind
191           (wonp error)
192         (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
193                             sb-unix:TIOCGPGRP
194                             (alien-sap (sb-alien:addr result)))
195       (unless wonp
196         (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
197       result))
198   (process-pid proc))
199
200 (defun process-kill (proc signal &optional (whom :pid))
201   "Hand SIGNAL to PROC. If WHOM is :PID, use the kill Unix system call. If
202    WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
203    :PTY-PROCESS-GROUP deliver the signal to whichever process group is
204    currently in the foreground."
205   (let ((pid (ecase whom
206                ((:pid :process-group)
207                 (process-pid proc))
208                (:pty-process-group
209                 #-hpux
210                 (find-current-foreground-process proc)))))
211     (multiple-value-bind
212           (okay errno)
213         (case whom
214           #+hpux
215           (:pty-process-group
216            (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
217                                sb-unix:TIOCSIGSEND
218                                (sb-sys:int-sap
219                                 (sb-unix:unix-signal-number signal))))
220           ((:process-group #-hpux :pty-process-group)
221            (sb-unix:unix-killpg pid signal))
222           (t
223            (sb-unix:unix-kill pid signal)))
224       (cond ((not okay)
225              (values nil errno))
226             ((and (eql pid (process-pid proc))
227                   (= (sb-unix:unix-signal-number signal)
228                      (sb-unix:unix-signal-number :sigcont)))
229              (setf (process-%status proc) :running)
230              (setf (process-exit-code proc) nil)
231              (when (process-status-hook proc)
232                (funcall (process-status-hook proc) proc))
233              t)
234             (t
235              t)))))
236
237 (defun process-alive-p (proc)
238   "Return T if the process is still alive, NIL otherwise."
239   (let ((status (process-status proc)))
240     (if (or (eq status :running)
241             (eq status :stopped))
242         t
243         nil)))
244
245 (defun process-close (proc)
246   "Close all streams connected to PROC and stop maintaining the status slot."
247   (macrolet ((frob (stream abort)
248                `(when ,stream (close ,stream :abort ,abort))))
249     (frob (process-pty    proc)   t) ; Don't FLUSH-OUTPUT to dead process, ..
250     (frob (process-input  proc)   t) ; .. 'cause it will generate SIGPIPE.
251     (frob (process-output proc) nil)
252     (frob (process-error  proc) nil))
253   (sb-sys:without-interrupts
254    (setf *active-processes* (delete proc *active-processes*)))
255   proc)
256
257 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
258 (defun sigchld-handler (ignore1 ignore2 ignore3)
259   (declare (ignore ignore1 ignore2 ignore3))
260   (get-processes-status-changes))
261
262 (defun get-processes-status-changes ()
263   (loop
264       (multiple-value-bind (pid what code core)
265           (wait3 t t)
266         (unless pid
267           (return))
268         (let ((proc (find pid *active-processes* :key #'process-pid)))
269           (when proc
270             (setf (process-%status proc) what)
271             (setf (process-exit-code proc) code)
272             (setf (process-core-dumped proc) core)
273             (when (process-status-hook proc)
274               (funcall (process-status-hook proc) proc))
275             (when (position what #(:exited :signaled))
276               (sb-sys:without-interrupts
277                (setf *active-processes*
278                      (delete proc *active-processes*)))))))))
279 \f
280 ;;;; RUN-PROGRAM and close friends
281
282 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
283 (defvar *close-on-error* nil)
284
285 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
286 (defvar *close-in-parent* nil)
287
288 ;;; list of handlers installed by RUN-PROGRAM
289 (defvar *handlers-installed* nil)
290
291 #+FreeBSD
292 (define-alien-type nil
293   (struct sgttyb
294           (sg-ispeed sb-alien:char)     ; input speed
295           (sg-ospeed sb-alien:char)     ; output speed
296           (sg-erase sb-alien:char)      ; erase character
297           (sg-kill sb-alien:char)       ; kill character
298           (sg-flags sb-alien:short)))   ; mode flags
299 #+OpenBSD
300 (define-alien-type nil
301   (struct sgttyb
302           (sg-four sb-alien:int)
303           (sg-chars (array sb-alien:char 4))
304           (sg-flags sb-alien:int)))
305
306 ;;; Find an unused pty. Return three values: the file descriptor for
307 ;;; the master side of the pty, the file descriptor for the slave side
308 ;;; of the pty, and the name of the tty device for the slave side.
309 (defun find-a-pty ()
310   (dolist (char '(#\p #\q))
311     (dotimes (digit 16)
312       (let* ((master-name (format nil "/dev/pty~C~X" char digit))
313              (master-fd (sb-unix:unix-open master-name
314                                            sb-unix:o_rdwr
315                                            #o666)))
316         (when master-fd
317           (let* ((slave-name (format nil "/dev/tty~C~X" char digit))
318                  (slave-fd (sb-unix:unix-open slave-name
319                                               sb-unix:o_rdwr
320                                               #o666)))
321             (when slave-fd
322               ;; comment from classic CMU CL:
323               ;;   Maybe put a vhangup here?
324               ;;
325               ;; FIXME: It seems as though this logic should be in
326               ;; OPEN-PTY, not FIND-A-PTY (both from the comments
327               ;; documenting DEFUN FIND-A-PTY, and from the
328               ;; connotations of the function names).
329               ;;
330               ;; FIXME: It would be nice to have a note, and/or a pointer
331               ;; to some reference material somewhere, explaining
332               ;; why we need this on *BSD and not on Linux.
333               #+bsd
334               (sb-alien:with-alien ((stuff (sb-alien:struct sgttyb)))
335                 (let ((sap (sb-alien:alien-sap stuff)))
336                   (sb-unix:unix-ioctl slave-fd sb-unix:TIOCGETP sap)
337                   (setf (sb-alien:slot stuff 'sg-flags)
338                         ;; This is EVENP|ODDP, the same numeric code
339                         ;; both on FreeBSD and on OpenBSD. -- WHN 20000929
340                         #o300) ; EVENP|ODDP
341                   (sb-unix:unix-ioctl slave-fd sb-unix:TIOCSETP sap)
342                   (sb-unix:unix-ioctl master-fd sb-unix:TIOCGETP sap)
343                   (setf (sb-alien:slot stuff 'sg-flags)
344                         (logand (sb-alien:slot stuff 'sg-flags)
345                                 ;; This is ~ECHO, the same numeric
346                                 ;; code both on FreeBSD and on OpenBSD.
347                                 ;; -- WHN 20000929
348                                 (lognot 8))) ; ~ECHO
349                   (sb-unix:unix-ioctl master-fd sb-unix:TIOCSETP sap)))
350               (return-from find-a-pty
351                 (values master-fd
352                         slave-fd
353                         slave-name)))
354             (sb-unix:unix-close master-fd))))))
355   (error "could not find a pty"))
356
357 (defun open-pty (pty cookie)
358   (when pty
359     (multiple-value-bind
360           (master slave name)
361         (find-a-pty)
362       (push master *close-on-error*)
363       (push slave *close-in-parent*)
364       (when (streamp pty)
365         (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
366           (unless new-fd
367             (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
368           (push new-fd *close-on-error*)
369           (copy-descriptor-to-stream new-fd pty cookie)))
370       (values name
371               (sb-sys:make-fd-stream master :input t :output t)))))
372
373 (defmacro round-bytes-to-words (n)
374   `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
375
376 (defun string-list-to-c-strvec (string-list)
377   ;; Make a pass over STRING-LIST to calculate the amount of memory
378   ;; needed to hold the strvec.
379   (let ((string-bytes 0)
380         ;; We need an extra for the null, and an extra 'cause exect
381         ;; clobbers argv[-1].
382         (vec-bytes (* #-alpha 4 #+alpha 8 (+ (length string-list) 2))))
383     (declare (fixnum string-bytes vec-bytes))
384     (dolist (s string-list)
385       (enforce-type s simple-string)
386       (incf string-bytes (round-bytes-to-words (1+ (length s)))))
387     ;; Now allocate the memory and fill it in.
388     (let* ((total-bytes (+ string-bytes vec-bytes))
389            (vec-sap (sb-sys:allocate-system-memory total-bytes))
390            (string-sap (sap+ vec-sap vec-bytes))
391            (i #-alpha 4 #+alpha 8))
392       (declare (type (and unsigned-byte fixnum) total-bytes i)
393                (type sb-sys:system-area-pointer vec-sap string-sap))
394       (dolist (s string-list)
395         (declare (simple-string s))
396         (let ((n (length s)))
397           ;; Blast the string into place.
398           (sb-kernel:copy-to-system-area (the simple-string s)
399                                          (* sb-vm:vector-data-offset
400                                             sb-vm:n-word-bits)
401                                          string-sap 0
402                                          (* (1+ n) sb-vm:n-byte-bits))
403           ;; Blast the pointer to the string into place.
404           (setf (sap-ref-sap vec-sap i) string-sap)
405           (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
406           (incf i #-alpha 4 #+alpha 8)))
407       ;; Blast in the last null pointer.
408       (setf (sap-ref-sap vec-sap i) (int-sap 0))
409       (values vec-sap (sap+ vec-sap #-alpha 4 #+alpha 8) total-bytes))))
410
411 (defmacro with-c-strvec ((var str-list) &body body)
412   (let ((sap (gensym "SAP-"))
413         (size (gensym "SIZE-")))
414     `(multiple-value-bind
415       (,sap ,var ,size)
416       (string-list-to-c-strvec ,str-list)
417       (unwind-protect
418            (progn
419              ,@body)
420         (sb-sys:deallocate-system-memory ,sap ,size)))))
421
422 (sb-alien:define-alien-routine spawn sb-alien:int
423   (program sb-alien:c-string)
424   (argv (* sb-alien:c-string))
425   (envp (* sb-alien:c-string))
426   (pty-name sb-alien:c-string)
427   (stdin sb-alien:int)
428   (stdout sb-alien:int)
429   (stderr sb-alien:int))
430
431 ;;; Is UNIX-FILENAME the name of a file that we can execute?
432 (defun unix-filename-is-executable-p (unix-filename)
433   (declare (type simple-string unix-filename))
434   (values (and (eq (sb-unix:unix-file-kind unix-filename) :file)
435                (sb-unix:unix-access unix-filename sb-unix:x_ok))))
436
437 ;;; FIXME: There shouldn't be two semiredundant versions of the
438 ;;; documentation. Since this is a public extension function, the
439 ;;; documentation should be in the doc string. So all information from
440 ;;; this comment should be merged into the doc string, and then this
441 ;;; comment can go away.
442 ;;;
443 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
444 ;;; Strange stuff happens to keep the Unix state of the world
445 ;;; coherent.
446 ;;;
447 ;;; The child process needs to get its input from somewhere, and send
448 ;;; its output (both standard and error) to somewhere. We have to do
449 ;;; different things depending on where these somewheres really are.
450 ;;;
451 ;;; For input, there are five options:
452 ;;;  -- T: Just leave fd 0 alone. Pretty simple.
453 ;;;  -- "file": Read from the file. We need to open the file and
454 ;;;     pull the descriptor out of the stream. The parent should close
455 ;;;     this stream after the child is up and running to free any 
456 ;;;     storage used in the parent.
457 ;;;  -- NIL: Same as "file", but use "/dev/null" as the file.
458 ;;;  -- :STREAM: Use Unix pipe() to create two descriptors. Use
459 ;;;     SB-SYS:MAKE-FD-STREAM to create the output stream on the
460 ;;;     writeable descriptor, and pass the readable descriptor to
461 ;;;     the child. The parent must close the readable descriptor for
462 ;;;     EOF to be passed up correctly.
463 ;;;  -- a stream: If it's a fd-stream, just pull the descriptor out
464 ;;;     of it. Otherwise make a pipe as in :STREAM, and copy 
465 ;;;     everything across.
466 ;;;
467 ;;; For output, there are five options:
468 ;;;  -- T: Leave descriptor 1 alone.
469 ;;;  -- "file": dump output to the file.
470 ;;;  -- NIL: dump output to /dev/null.
471 ;;;  -- :STREAM: return a stream that can be read from.
472 ;;;  -- a stream: if it's a fd-stream, use the descriptor in it.
473 ;;;     Otherwise, copy stuff from output to stream.
474 ;;;
475 ;;; For error, there are all the same options as output plus:
476 ;;;  -- :OUTPUT: redirect to the same place as output.
477 ;;;
478 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
479 ;;; the fork worked, and NIL if it did not.
480 (defun run-program (program args
481                     &key
482                     (env nil env-p)
483                     (environment (if env-p
484                                      (unix-environment-sbcl-from-cmucl env)
485                                      (posix-environ))
486                                  environment-p)
487                     (wait t)
488                     pty
489                     input
490                     if-input-does-not-exist
491                     output
492                     (if-output-exists :error)
493                     (error :output)
494                     (if-error-exists :error)
495                     status-hook)
496   "RUN-PROGRAM creates a new Unix process running the Unix program found in
497    the file specified by the PROGRAM argument.  ARGS are the standard
498    arguments that can be passed to a Unix program. For no arguments, use NIL
499    (which means that just the name of the program is passed as arg 0).
500
501    RUN-PROGRAM will either return NIL or a PROCESS structure.  See the CMU
502    Common Lisp Users Manual for details about the PROCESS structure.
503
504    notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
505      1. The SBCL implementation of RUN-PROGRAM, like Perl and many other
506         programs, but unlike the original CMU CL implementation, copies
507         the Unix environment by default.
508      2. Running Unix programs from a setuid process, or in any other
509         situation where the Unix environment is under the control of someone
510         else, is a mother lode of security problems. If you are contemplating
511         doing this, read about it first. (The Perl community has a lot of good
512         documentation about this and other security issues in script-like
513         programs.)
514
515    The &KEY arguments have the following meanings:
516      :ENVIRONMENT
517         a list of SIMPLE-STRINGs describing the new Unix environment (as
518         in \"man environ\"). The default is to copy the environment of
519         the current process.
520      :ENV
521         an alternative lossy representation of the new Unix environment,
522         for compatibility with CMU CL
523      :WAIT
524         If non-NIL (default), wait until the created process finishes.  If
525         NIL, continue running Lisp until the program finishes.
526      :PTY
527         Either T, NIL, or a stream.  Unless NIL, the subprocess is established
528         under a PTY.  If :pty is a stream, all output to this pty is sent to
529         this stream, otherwise the PROCESS-PTY slot is filled in with a stream
530         connected to pty that can read output and write input.
531      :INPUT
532         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
533         input for the current process is inherited.  If NIL, /dev/null
534         is used.  If a pathname, the file so specified is used.  If a stream,
535         all the input is read from that stream and send to the subprocess.  If
536         :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends 
537         its output to the process. Defaults to NIL.
538      :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
539         can be one of:
540            :ERROR to generate an error
541            :CREATE to create an empty file
542            NIL (the default) to return NIL from RUN-PROGRAM
543      :OUTPUT 
544         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
545         output for the current process is inherited.  If NIL, /dev/null
546         is used.  If a pathname, the file so specified is used.  If a stream,
547         all the output from the process is written to this stream. If
548         :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
549         be read to get the output. Defaults to NIL.
550      :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
551         can be one of:
552            :ERROR (the default) to generate an error
553            :SUPERSEDE to supersede the file with output from the program
554            :APPEND to append output from the program to the file 
555            NIL to return NIL from RUN-PROGRAM, without doing anything
556      :ERROR and :IF-ERROR-EXISTS
557         Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
558         specified as :OUTPUT in which case all error output is routed to the
559         same place as normal output.
560      :STATUS-HOOK
561         This is a function the system calls whenever the status of the
562         process changes.  The function takes the process as an argument."
563
564   (when (and env-p environment-p)
565     (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
566   ;; Make sure that the interrupt handler is installed.
567   (sb-sys:enable-interrupt :sigchld #'sigchld-handler)
568   ;; Prepend the program to the argument list.
569   (push (namestring program) args)
570   (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
571         ;; communicate cleanup info.
572         *close-on-error*
573         *close-in-parent*
574         *handlers-installed*
575         ;; Establish PROC at this level so that we can return it.
576         proc
577         ;; It's friendly to allow the caller to pass any string
578         ;; designator, but internally we'd like SIMPLE-STRINGs.
579         (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
580     (unwind-protect
581          (let (;; FIXME: The old code here used to do
582                ;;   (MERGE-PATHNAMES PROGRAM "path:"),
583                ;; which is the right idea (searching through the Unix
584                ;; PATH). Unfortunately, there is no logical pathname
585                ;; "path:" defined in sbcl-0.6.10. It would probably be 
586                ;; reasonable to restore Unix PATH searching in SBCL, e.g.
587                ;; with a function FIND-EXECUTABLE-FILE-IN-POSIX-PATH.
588                ;; CMU CL did it with a "PATH:" search list, but CMU CL
589                ;; search lists are a non-ANSI extension that SBCL
590                ;; doesn't support. -- WHN)
591                (pfile (unix-namestring program t))
592                (cookie (list 0)))
593            (unless pfile
594              (error "no such program: ~S" program))
595            (unless (unix-filename-is-executable-p pfile)
596              (error "not executable: ~S" program))
597            (multiple-value-bind (stdin input-stream)
598                (get-descriptor-for input cookie
599                                    :direction :input
600                                    :if-does-not-exist if-input-does-not-exist)
601              (multiple-value-bind (stdout output-stream)
602                  (get-descriptor-for output cookie
603                                      :direction :output
604                                      :if-exists if-output-exists)
605                (multiple-value-bind (stderr error-stream)
606                    (if (eq error :output)
607                        (values stdout output-stream)
608                        (get-descriptor-for error cookie
609                                            :direction :output
610                                            :if-exists if-error-exists))
611                  (multiple-value-bind (pty-name pty-stream)
612                      (open-pty pty cookie)
613                    ;; Make sure we are not notified about the child
614                    ;; death before we have installed the PROCESS
615                    ;; structure in *ACTIVE-PROCESSES*.
616                    (sb-sys:without-interrupts
617                     (with-c-strvec (args-vec simple-args)
618                       (with-c-strvec (environment-vec environment)
619                         (let ((child-pid
620                                (without-gcing
621                                 (spawn pfile args-vec environment-vec pty-name
622                                        stdin stdout stderr))))
623                           (when (< child-pid 0)
624                             (error "couldn't fork child process: ~A"
625                                    (strerror)))
626                           (setf proc (make-process :pid child-pid
627                                                    :%status :running
628                                                    :pty pty-stream
629                                                    :input input-stream
630                                                    :output output-stream
631                                                    :error error-stream
632                                                    :status-hook status-hook
633                                                    :cookie cookie))
634                           (push proc *active-processes*))))))))))
635       (dolist (fd *close-in-parent*)
636         (sb-unix:unix-close fd))
637       (unless proc
638         (dolist (fd *close-on-error*)
639           (sb-unix:unix-close fd))
640         (dolist (handler *handlers-installed*)
641           (sb-sys:remove-fd-handler handler))))
642     (when (and wait proc)
643       (process-wait proc))
644     proc))
645
646 ;;; Install a handler for any input that shows up on the file
647 ;;; descriptor. The handler reads the data and writes it to the
648 ;;; stream.
649 (defun copy-descriptor-to-stream (descriptor stream cookie)
650   (incf (car cookie))
651   (let ((string (make-string 256))
652         handler)
653     (setf handler
654           (sb-sys:add-fd-handler
655            descriptor
656            :input (lambda (fd)
657                     (declare (ignore fd))
658                     (loop
659                      (unless handler
660                        (return))
661                      (multiple-value-bind
662                          (result readable/errno)
663                          (sb-unix:unix-select (1+ descriptor)
664                                               (ash 1 descriptor)
665                                               0 0 0)
666                        (cond ((null result)
667                               (error "~@<couldn't select on sub-process: ~
668                                            ~2I~_~A~:>"
669                                      (strerror readable/errno)))
670                              ((zerop result)
671                               (return))))
672                      (sb-alien:with-alien ((buf (sb-alien:array
673                                                  sb-alien:char
674                                                  256)))
675                        (multiple-value-bind
676                            (count errno)
677                            (sb-unix:unix-read descriptor
678                                               (alien-sap buf)
679                                               256)
680                          (cond ((or (and (null count)
681                                          (eql errno sb-unix:eio))
682                                     (eql count 0))
683                                 (sb-sys:remove-fd-handler handler)
684                                 (setf handler nil)
685                                 (decf (car cookie))
686                                 (sb-unix:unix-close descriptor)
687                                 (return))
688                                ((null count)
689                                 (sb-sys:remove-fd-handler handler)
690                                 (setf handler nil)
691                                 (decf (car cookie))
692                                 (error
693                                  "~@<couldn't read input from sub-process: ~
694                                      ~2I~_~A~:>"
695                                  (strerror errno)))
696                                (t
697                                 (sb-kernel:copy-from-system-area
698                                  (alien-sap buf) 0
699                                  string (* sb-vm:vector-data-offset
700                                            sb-vm:n-word-bits)
701                                  (* count sb-vm:n-byte-bits))
702                                 (write-string string stream
703                                               :end count)))))))))))
704
705 ;;; Find a file descriptor to use for object given the direction.
706 ;;; Returns the descriptor. If object is :STREAM, returns the created
707 ;;; stream as the second value.
708 (defun get-descriptor-for (object
709                            cookie
710                            &rest keys
711                            &key direction
712                            &allow-other-keys)
713   (cond ((eq object t)
714          ;; No new descriptor is needed.
715          (values -1 nil))
716         ((eq object nil)
717          ;; Use /dev/null.
718          (multiple-value-bind
719                (fd errno)
720              (sb-unix:unix-open "/dev/null"
721                                 (case direction
722                                   (:input sb-unix:o_rdonly)
723                                   (:output sb-unix:o_wronly)
724                                   (t sb-unix:o_rdwr))
725                                 #o666)
726            (unless fd
727              (error "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
728                     (strerror errno)))
729            (push fd *close-in-parent*)
730            (values fd nil)))
731         ((eq object :stream)
732          (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
733            (unless read-fd
734              (error "couldn't create pipe: ~A" (strerror write-fd)))
735            (case direction
736              (:input
737               (push read-fd *close-in-parent*)
738               (push write-fd *close-on-error*)
739               (let ((stream (sb-sys:make-fd-stream write-fd :output t)))
740                 (values read-fd stream)))
741              (:output
742               (push read-fd *close-on-error*)
743               (push write-fd *close-in-parent*)
744               (let ((stream (sb-sys:make-fd-stream read-fd :input t)))
745                 (values write-fd stream)))
746              (t
747               (sb-unix:unix-close read-fd)
748               (sb-unix:unix-close write-fd)
749               (error "Direction must be either :INPUT or :OUTPUT, not ~S."
750                      direction)))))
751         ((or (pathnamep object) (stringp object))
752          (with-open-stream (file (apply #'open object keys))
753            (multiple-value-bind
754                  (fd errno)
755                (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
756              (cond (fd
757                     (push fd *close-in-parent*)
758                     (values fd nil))
759                    (t
760                     (error "couldn't duplicate file descriptor: ~A"
761                            (strerror errno)))))))
762         ((sb-sys:fd-stream-p object)
763          (values (sb-sys:fd-stream-fd object) nil))
764         ((streamp object)
765          (ecase direction
766            (:input
767             ;; FIXME: We could use a better way of setting up
768             ;; temporary files, both here and in LOAD-FOREIGN.
769             (dotimes (count
770                        256
771                       (error "could not open a temporary file in /tmp"))
772               (let* ((name (format nil "/tmp/.run-program-~D" count))
773                      (fd (sb-unix:unix-open name
774                                             (logior sb-unix:o_rdwr
775                                                     sb-unix:o_creat
776                                                     sb-unix:o_excl)
777                                             #o666)))
778                 (sb-unix:unix-unlink name)
779                 (when fd
780                   (let ((newline (string #\Newline)))
781                     (loop
782                         (multiple-value-bind
783                               (line no-cr)
784                             (read-line object nil nil)
785                           (unless line
786                             (return))
787                           (sb-unix:unix-write fd line 0 (length line))
788                           (if no-cr
789                               (return)
790                               (sb-unix:unix-write fd newline 0 1)))))
791                   (sb-unix:unix-lseek fd 0 sb-unix:l_set)
792                   (push fd *close-in-parent*)
793                   (return (values fd nil))))))
794            (:output
795             (multiple-value-bind (read-fd write-fd)
796                 (sb-unix:unix-pipe)
797               (unless read-fd
798                 (error "couldn't create pipe: ~S" (strerror write-fd)))
799               (copy-descriptor-to-stream read-fd object cookie)
800               (push read-fd *close-on-error*)
801               (push write-fd *close-in-parent*)
802               (values write-fd nil)))))
803         (t
804          (error "invalid option to RUN-PROGRAM: ~S" object))))