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