cleanup related to RAW's port of RUN-PROGRAM:
[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-EXT")
14
15 (file-comment
16   "$Header$")
17 \f
18 ;;;; Import wait3(2) from Unix.
19
20 (sb-alien:def-alien-routine ("wait3" c-wait3) sb-c-call:int
21   (status sb-c-call:int :out)
22   (options sb-c-call:int)
23   (rusage sb-c-call:int))
24
25 (eval-when (load eval compile)
26   (defconstant wait-wnohang #-svr4 1 #+svr4 #o100)
27   (defconstant wait-wuntraced #-svr4 2 #+svr4 4)
28   (defconstant wait-wstopped #-svr4 #o177 #+svr4 wait-wuntraced))
29
30 (defun wait3 (&optional do-not-hang check-for-stopped)
31   "Return any available status information on child process. "
32   (multiple-value-bind (pid status)
33       (c-wait3 (logior (if do-not-hang
34                            wait-wnohang
35                            0)
36                        (if check-for-stopped
37                            wait-wuntraced
38                            0))
39                0)
40     (cond ((or (minusp pid)
41                (zerop pid))
42            nil)
43           ((eql (ldb (byte 8 0) status)
44                 wait-wstopped)
45            (values pid
46                    :stopped
47                    (ldb (byte 8 8) status)))
48           ((zerop (ldb (byte 7 0) status))
49            (values pid
50                    :exited
51                    (ldb (byte 8 8) status)))
52           (t
53            (let ((signal (ldb (byte 7 0) status)))
54              (values pid
55                      (if (or (eql signal sb-unix:sigstop)
56                              (eql signal sb-unix:sigtstp)
57                              (eql signal sb-unix:sigttin)
58                              (eql signal sb-unix:sigttou))
59                          :stopped
60                          :signaled)
61                      signal
62                      (not (zerop (ldb (byte 1 7) status)))))))))
63 \f
64 ;;;; process control stuff
65
66 (defvar *active-processes* nil
67   "List of process structures for all active processes.")
68
69 (defstruct (process)
70   pid                 ; PID of child process
71   %status             ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
72   exit-code           ; either exit code or signal
73   core-dumped         ; T if a core image was dumped
74   pty                 ; stream to child's pty, or NIL
75   input               ; stream to child's input, or NIL
76   output              ; stream from child's output, or NIL
77   error               ; stream from child's error output, or NIL
78   status-hook         ; closure to call when PROC changes status
79   plist               ; a place for clients to stash things
80   cookie)             ; list of the number of pipes from the subproc
81
82 (defmethod print-object ((process process) stream)
83   (print-unreadable-object (process stream :type t)
84     (format stream
85             "~D ~S"
86             (process-pid process)
87             (process-status process)))
88   process)
89
90 (defun process-status (proc)
91   "Return the current status of process.  The result is one of :RUNNING,
92    :STOPPED, :EXITED, or :SIGNALED."
93   (get-processes-status-changes)
94   (process-%status proc))
95
96 (defun process-wait (proc &optional check-for-stopped)
97   "Wait for PROC to quit running for some reason.  Returns PROC."
98   (loop
99       (case (process-status proc)
100         (:running)
101         (:stopped
102          (when check-for-stopped
103            (return)))
104         (t
105          (when (zerop (car (process-cookie proc)))
106            (return))))
107       (sb-sys:serve-all-events 1))
108   proc)
109
110 #-hpux
111 ;;; Find the current foreground process group id.
112 (defun find-current-foreground-process (proc)
113   (sb-alien:with-alien ((result sb-c-call:int))
114     (multiple-value-bind
115           (wonp error)
116         (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
117                             sb-unix:TIOCGPGRP
118                             (sb-alien:alien-sap (sb-alien:addr result)))
119       (unless wonp
120         (error "TIOCPGRP ioctl failed: ~S"
121                (sb-unix:get-unix-error-msg error)))
122       result))
123   (process-pid proc))
124
125 (defun process-kill (proc signal &optional (whom :pid))
126   "Hand SIGNAL to PROC.  If whom is :pid, use the kill Unix system call.  If
127    whom is :process-group, use the killpg Unix system call.  If whom is
128    :pty-process-group deliver the signal to whichever process group is currently
129    in the foreground."
130   (let ((pid (ecase whom
131                ((:pid :process-group)
132                 (process-pid proc))
133                (:pty-process-group
134                 #-hpux
135                 (find-current-foreground-process proc)))))
136     (multiple-value-bind
137           (okay errno)
138         (case whom
139           #+hpux
140           (:pty-process-group
141            (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
142                                sb-unix:TIOCSIGSEND
143                                (sb-sys:int-sap
144                                 (sb-unix:unix-signal-number signal))))
145           ((:process-group #-hpux :pty-process-group)
146            (sb-unix:unix-killpg pid signal))
147           (t
148            (sb-unix:unix-kill pid signal)))
149       (cond ((not okay)
150              (values nil errno))
151             ((and (eql pid (process-pid proc))
152                   (= (sb-unix:unix-signal-number signal) sb-unix:sigcont))
153              (setf (process-%status proc) :running)
154              (setf (process-exit-code proc) nil)
155              (when (process-status-hook proc)
156                (funcall (process-status-hook proc) proc))
157              t)
158             (t
159              t)))))
160
161 (defun process-alive-p (proc)
162   "Return T if the process is still alive, NIL otherwise."
163   (let ((status (process-status proc)))
164     (if (or (eq status :running)
165             (eq status :stopped))
166         t
167         nil)))
168
169 (defun process-close (proc)
170   "Close all streams connected to PROC and stop maintaining the status slot."
171   (macrolet ((frob (stream abort)
172                `(when ,stream (close ,stream :abort ,abort))))
173     (frob (process-pty    proc)   t) ; Don't FLUSH-OUTPUT to dead process, ..
174     (frob (process-input  proc)   t) ; .. 'cause it will generate SIGPIPE.
175     (frob (process-output proc) nil)
176     (frob (process-error  proc) nil))
177   (sb-sys:without-interrupts
178    (setf *active-processes* (delete proc *active-processes*)))
179   proc)
180
181 ;;; the handler for sigchld signals that RUN-PROGRAM establishes
182 (defun sigchld-handler (ignore1 ignore2 ignore3)
183   (declare (ignore ignore1 ignore2 ignore3))
184   (get-processes-status-changes))
185
186 (defun get-processes-status-changes ()
187   (loop
188       (multiple-value-bind (pid what code core)
189           (wait3 t t)
190         (unless pid
191           (return))
192         (let ((proc (find pid *active-processes* :key #'process-pid)))
193           (when proc
194             (setf (process-%status proc) what)
195             (setf (process-exit-code proc) code)
196             (setf (process-core-dumped proc) core)
197             (when (process-status-hook proc)
198               (funcall (process-status-hook proc) proc))
199             (when (or (eq what :exited)
200                       (eq what :signaled))
201               (sb-sys:without-interrupts
202                (setf *active-processes*
203                      (delete proc *active-processes*)))))))))
204 \f
205 ;;;; RUN-PROGRAM and close friends
206
207 (defvar *close-on-error* nil
208   "List of file descriptors to close when RUN-PROGRAM exits due to an error.")
209 (defvar *close-in-parent* nil
210   "List of file descriptors to close when RUN-PROGRAM returns in the parent.")
211 (defvar *handlers-installed* nil
212   "List of handlers installed by RUN-PROGRAM.")
213
214 #+FreeBSD
215 (def-alien-type nil
216     (struct sgttyb
217             (sg-ispeed sb-c-call:char)  ; input speed
218             (sg-ospeed sb-c-call:char)  ; output speed
219             (sg-erase sb-c-call:char)   ; erase character
220             (sg-kill sb-c-call:char)    ; kill character
221             (sg-flags sb-c-call:short)  ; mode flags
222             ))
223
224 ;;; Find a pty that is not in use. Return three values: the file
225 ;;; descriptor for the master side of the pty, the file descriptor for
226 ;;; the slave side of the pty, and the name of the tty device for the
227 ;;; slave side.
228 (defun find-a-pty ()
229   (dolist (char '(#\p #\q))
230     (dotimes (digit 16)
231       (let* ((master-name (format nil "/dev/pty~C~X" char digit))
232              (master-fd (sb-unix:unix-open master-name
233                                            sb-unix:o_rdwr
234                                            #o666)))
235         (when master-fd
236           (let* ((slave-name (format nil "/dev/tty~C~X" char digit))
237                  (slave-fd (sb-unix:unix-open slave-name
238                                               sb-unix:o_rdwr
239                                               #o666)))
240             (when slave-fd
241                                         ; Maybe put a vhangup here?
242               #-linux
243               (sb-alien:with-alien ((stuff (sb-alien:struct sgttyb)))
244                 (let ((sap (sb-alien:alien-sap stuff)))
245                   (sb-unix:unix-ioctl slave-fd sb-unix:TIOCGETP sap)
246                   (setf (sb-alien:slot stuff 'sg-flags)
247                         #o300)          ; EVENP|ODDP
248                   (sb-unix:unix-ioctl slave-fd sb-unix:TIOCSETP sap)
249                   (sb-unix:unix-ioctl master-fd sb-unix:TIOCGETP sap)
250                   (setf (sb-alien:slot stuff 'sg-flags)
251                         (logand (sb-alien:slot stuff 'sg-flags)
252                                 (lognot 8))) ; ~ECHO
253                   (sb-unix:unix-ioctl master-fd sb-unix:TIOCSETP sap)))
254               (return-from find-a-pty
255                 (values master-fd
256                         slave-fd
257                         slave-name)))
258             (sb-unix:unix-close master-fd))))))
259   (error "could not find a pty"))
260
261 (defun open-pty (pty cookie)
262   (when pty
263     (multiple-value-bind
264           (master slave name)
265         (find-a-pty)
266       (push master *close-on-error*)
267       (push slave *close-in-parent*)
268       (when (streamp pty)
269         (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
270           (unless new-fd
271             (error "could not SB-UNIX:UNIX-DUP ~D: ~S"
272                    master (sb-unix:get-unix-error-msg errno)))
273           (push new-fd *close-on-error*)
274           (copy-descriptor-to-stream new-fd pty cookie)))
275       (values name
276               (sb-sys:make-fd-stream master :input t :output t)))))
277
278 (defmacro round-bytes-to-words (n)
279   `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
280
281 (defun string-list-to-c-strvec (string-list)
282   ;; Make a pass over STRING-LIST to calculate the amount of memory
283   ;; needed to hold the strvec.
284   (let ((string-bytes 0)
285         ;; We need an extra for the null, and an extra 'cause exect
286         ;; clobbers argv[-1].
287         (vec-bytes (* #-alpha 4 #+alpha 8 (+ (length string-list) 2))))
288     (declare (fixnum string-bytes vec-bytes))
289     (dolist (s string-list)
290       (check-type s simple-string)
291       (incf string-bytes (round-bytes-to-words (1+ (length s)))))
292     ;; Now allocate the memory and fill it in.
293     (let* ((total-bytes (+ string-bytes vec-bytes))
294            (vec-sap (sb-sys:allocate-system-memory total-bytes))
295            (string-sap (sap+ vec-sap vec-bytes))
296            (i #-alpha 4 #+alpha 8))
297       (declare (type (and unsigned-byte fixnum) total-bytes i)
298                (type sb-sys:system-area-pointer vec-sap string-sap))
299       (dolist (s string-list)
300         (declare (simple-string s))
301         (let ((n (length s)))
302           ;; Blast the string into place.
303           (sb-kernel:copy-to-system-area (the simple-string s)
304                                          (* sb-vm:vector-data-offset
305                                             sb-vm:word-bits)
306                                          string-sap 0
307                                          (* (1+ n) sb-vm:byte-bits))
308           ;; Blast the pointer to the string into place.
309           (setf (sap-ref-sap vec-sap i) string-sap)
310           (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
311           (incf i #-alpha 4 #+alpha 8)))
312       ;; Blast in the last null pointer.
313       (setf (sap-ref-sap vec-sap i) (int-sap 0))
314       (values vec-sap (sap+ vec-sap #-alpha 4 #+alpha 8) total-bytes))))
315
316 (defmacro with-c-strvec ((var str-list) &body body)
317   (let ((sap (gensym "SAP-"))
318         (size (gensym "SIZE-")))
319     `(multiple-value-bind
320       (,sap ,var ,size)
321       (string-list-to-c-strvec ,str-list)
322       (unwind-protect
323            (progn
324              ,@body)
325         (sb-sys:deallocate-system-memory ,sap ,size)))))
326
327 (sb-alien:def-alien-routine spawn sb-c-call:int
328   (program sb-c-call:c-string)
329   (argv (* sb-c-call:c-string))
330   (envp (* sb-c-call:c-string))
331   (pty-name sb-c-call:c-string)
332   (stdin sb-c-call:int)
333   (stdout sb-c-call:int)
334   (stderr sb-c-call:int))
335
336 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
337 ;;; Strange stuff happens to keep the Unix state of the world
338 ;;; coherent.
339 ;;;
340 ;;; The child process needs to get its input from somewhere, and send
341 ;;; its output (both standard and error) to somewhere. We have to do
342 ;;; different things depending on where these somewheres really are.
343 ;;;
344 ;;; For input, there are five options:
345 ;;;  -- T: Just leave fd 0 alone. Pretty simple.
346 ;;;  -- "file": Read from the file. We need to open the file and
347 ;;;     pull the descriptor out of the stream. The parent should close
348 ;;;     this stream after the child is up and running to free any 
349 ;;;     storage used in the parent.
350 ;;;  -- NIL: Same as "file", but use "/dev/null" as the file.
351 ;;;  -- :STREAM: Use Unix pipe() to create two descriptors. Use
352 ;;;     SB-SYS:MAKE-FD-STREAM to create the output stream on the
353 ;;;     writeable descriptor, and pass the readable descriptor to
354 ;;;     the child. The parent must close the readable descriptor for
355 ;;;     EOF to be passed up correctly.
356 ;;;  -- a stream: If it's a fd-stream, just pull the descriptor out
357 ;;;     of it. Otherwise make a pipe as in :STREAM, and copy 
358 ;;;     everything across.
359 ;;;
360 ;;; For output, there are five options:
361 ;;;  -- T: Leave descriptor 1 alone.
362 ;;;  -- "file": dump output to the file.
363 ;;;  -- NIL: dump output to /dev/null.
364 ;;;  -- :STREAM: return a stream that can be read from.
365 ;;;  -- a stream: if it's a fd-stream, use the descriptor in it.
366 ;;;     Otherwise, copy stuff from output to stream.
367 ;;;
368 ;;; For error, there are all the same options as output plus:
369 ;;;  -- :OUTPUT: redirect to the same place as output.
370 ;;;
371 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
372 ;;; the fork worked, and NIL if it did not.
373 (defun run-program (program args
374                     &key env (wait t) pty input
375                     if-input-does-not-exist output (if-output-exists :error)
376                     (error :output) (if-error-exists :error) status-hook)
377   "RUN-PROGRAM creates a new process and runs the unix progam in the
378    file specified by the simple-string program.  Args are the standard
379    arguments that can be passed to a Unix program, for no arguments
380    use NIL (which means just the name of the program is passed as arg 0).
381
382    RUN-PROGRAM will either return NIL or a PROCESS structure.  See the CMU
383    Common Lisp Users Manual for details about the PROCESS structure.
384
385    The keyword arguments have the following meanings:
386      :ENV
387         An A-LIST mapping keyword environment variables to simple-string
388         values.
389      :WAIT
390         If non-NIL (default), wait until the created process finishes.  If
391         NIL, continue running Lisp until the program finishes.
392      :PTY
393         Either T, NIL, or a stream.  Unless NIL, the subprocess is established
394         under a PTY.  If :pty is a stream, all output to this pty is sent to
395         this stream, otherwise the PROCESS-PTY slot is filled in with a stream
396         connected to pty that can read output and write input.
397      :INPUT
398         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
399         input for the current process is inherited.  If NIL, /dev/null
400         is used.  If a pathname, the file so specified is used.  If a stream,
401         all the input is read from that stream and send to the subprocess.  If
402         :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends 
403         its output to the process. Defaults to NIL.
404      :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
405         can be one of:
406            :ERROR to generate an error
407            :CREATE to create an empty file
408            NIL (the default) to return NIL from RUN-PROGRAM
409      :OUTPUT 
410         Either T, NIL, a pathname, a stream, or :STREAM.  If T, the standard
411         output for the current process is inherited.  If NIL, /dev/null
412         is used.  If a pathname, the file so specified is used.  If a stream,
413         all the output from the process is written to this stream. If
414         :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
415         be read to get the output. Defaults to NIL.
416      :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
417         can be one of:
418            :ERROR (the default) to generate an error
419            :SUPERSEDE to supersede the file with output from the program
420            :APPEND to append output from the program to the file 
421            NIL to return NIL from RUN-PROGRAM, without doing anything
422      :ERROR and :IF-ERROR-EXISTS
423         Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
424         specified as :OUTPUT in which case all error output is routed to the
425         same place as normal output.
426      :STATUS-HOOK
427         This is a function the system calls whenever the status of the
428         process changes.  The function takes the process as an argument."
429
430   ;; Make sure that the interrupt handler is installed.
431   (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
432   ;; Make sure that all the args are okay.
433   (unless (every #'simple-string-p args)
434     (error "All arguments to program must be simple strings: ~S" args))
435   ;; Prepend the program to the argument list.
436   (push (namestring program) args)
437   ;; Clear various specials used by GET-DESCRIPTOR-FOR to communicate
438   ;; cleanup info.  Also, establish proc at this level so we can
439   ;; return it.
440   (let (*close-on-error* *close-in-parent* *handlers-installed* proc)
441     (unwind-protect
442          (let ((pfile (unix-namestring (merge-pathnames program "path:") t t))
443                (cookie (list 0)))
444            (unless pfile
445              (error "no such program: ~S" program))
446            (multiple-value-bind
447                  (stdin input-stream)
448                (get-descriptor-for input cookie :direction :input
449                                    :if-does-not-exist if-input-does-not-exist)
450              (multiple-value-bind
451                    (stdout output-stream)
452                  (get-descriptor-for output cookie :direction :output
453                                      :if-exists if-output-exists)
454                (multiple-value-bind
455                      (stderr error-stream)
456                    (if (eq error :output)
457                        (values stdout output-stream)
458                        (get-descriptor-for error cookie :direction :output
459                                            :if-exists if-error-exists))
460                  (multiple-value-bind (pty-name pty-stream)
461                      (open-pty pty cookie)
462                    ;; Make sure we are not notified about the child
463                    ;; death before we have installed the PROCESS
464                    ;; structure in *ACTIVE-PROCESSES*.
465                    (sb-sys:without-interrupts
466                     (with-c-strvec (argv args)
467                       (with-c-strvec
468                           (envp (mapcar #'(lambda (entry)
469                                             (concatenate
470                                              'string
471                                              (symbol-name (car entry))
472                                              "="
473                                              (cdr entry)))
474                                         env))
475                         (let ((child-pid
476                                (without-gcing
477                                 (spawn pfile argv envp pty-name
478                                        stdin stdout stderr))))
479                           (when (< child-pid 0)
480                             (error "could not fork child process: ~S"
481                                    (sb-unix:get-unix-error-msg)))
482                           (setf proc (make-process :pid child-pid
483                                                    :%status :running
484                                                    :pty pty-stream
485                                                    :input input-stream
486                                                    :output output-stream
487                                                    :error error-stream
488                                                    :status-hook status-hook
489                                                    :cookie cookie))
490                           (push proc *active-processes*))))))))))
491       (dolist (fd *close-in-parent*)
492         (sb-unix:unix-close fd))
493       (unless proc
494         (dolist (fd *close-on-error*)
495           (sb-unix:unix-close fd))
496         (dolist (handler *handlers-installed*)
497           (sb-sys:remove-fd-handler handler))))
498     (when (and wait proc)
499       (process-wait proc))
500     proc))
501
502 ;;; COPY-DESCRIPTOR-TO-STREAM -- internal
503 ;;;
504 ;;;   Installs a handler for any input that shows up on the file descriptor.
505 ;;; The handler reads the data and writes it to the stream.
506 ;;; 
507 (defun copy-descriptor-to-stream (descriptor stream cookie)
508   (incf (car cookie))
509   (let ((string (make-string 256))
510         handler)
511     (setf handler
512           (sb-sys:add-fd-handler
513            descriptor
514            :input #'(lambda (fd)
515                       (declare (ignore fd))
516                       (loop
517                           (unless handler
518                             (return))
519                           (multiple-value-bind
520                                 (result readable/errno)
521                               (sb-unix:unix-select (1+ descriptor)
522                                                    (ash 1 descriptor)
523                                                    0 0 0)
524                             (cond ((null result)
525                                    (error "could not select on sub-process: ~S"
526                                           (sb-unix:get-unix-error-msg
527                                            readable/errno)))
528                                   ((zerop result)
529                                    (return))))
530                         (sb-alien:with-alien ((buf (sb-alien:array
531                                                     sb-c-call:char
532                                                     256)))
533                           (multiple-value-bind
534                                 (count errno)
535                               (sb-unix:unix-read descriptor
536                                                  (alien-sap buf)
537                                                  256)
538                             (cond ((or (and (null count)
539                                             (eql errno sb-unix:eio))
540                                        (eql count 0))
541                                    (sb-sys:remove-fd-handler handler)
542                                    (setf handler nil)
543                                    (decf (car cookie))
544                                    (sb-unix:unix-close descriptor)
545                                    (return))
546                                   ((null count)
547                                    (sb-sys:remove-fd-handler handler)
548                                    (setf handler nil)
549                                    (decf (car cookie))
550                                    (error "could not read input from sub-process: ~S"
551                                           (sb-unix:get-unix-error-msg errno)))
552                                   (t
553                                    (sb-kernel:copy-from-system-area
554                                     (alien-sap buf) 0
555                                     string (* sb-vm:vector-data-offset
556                                               sb-vm:word-bits)
557                                     (* count sb-vm:byte-bits))
558                                    (write-string string stream
559                                                  :end count)))))))))))
560
561 ;;; Find a file descriptor to use for object given the direction.
562 ;;; Returns the descriptor. If object is :STREAM, returns the created
563 ;;; stream as the second value.
564 (defun get-descriptor-for (object
565                            cookie
566                            &rest keys
567                            &key direction
568                            &allow-other-keys)
569   (cond ((eq object t)
570          ;; No new descriptor is needed.
571          (values -1 nil))
572         ((eq object nil)
573          ;; Use /dev/null.
574          (multiple-value-bind
575                (fd errno)
576              (sb-unix:unix-open "/dev/null"
577                                 (case direction
578                                   (:input sb-unix:o_rdonly)
579                                   (:output sb-unix:o_wronly)
580                                   (t sb-unix:o_rdwr))
581                                 #o666)
582            (unless fd
583              (error "could not open \"/dev/null\": ~S"
584                     (sb-unix:get-unix-error-msg errno)))
585            (push fd *close-in-parent*)
586            (values fd nil)))
587         ((eq object :stream)
588          (multiple-value-bind
589                (read-fd write-fd)
590              (sb-unix:unix-pipe)
591            (unless read-fd
592              (error "could not create pipe: ~S"
593                     (sb-unix:get-unix-error-msg write-fd)))
594            (case direction
595              (:input
596               (push read-fd *close-in-parent*)
597               (push write-fd *close-on-error*)
598               (let ((stream (sb-sys:make-fd-stream write-fd :output t)))
599                 (values read-fd stream)))
600              (:output
601               (push read-fd *close-on-error*)
602               (push write-fd *close-in-parent*)
603               (let ((stream (sb-sys:make-fd-stream read-fd :input t)))
604                 (values write-fd stream)))
605              (t
606               (sb-unix:unix-close read-fd)
607               (sb-unix:unix-close write-fd)
608               (error "Direction must be either :INPUT or :OUTPUT, not ~S."
609                      direction)))))
610         ((or (pathnamep object) (stringp object))
611          (with-open-stream (file (apply #'open object keys))
612            (multiple-value-bind
613                  (fd errno)
614                (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
615              (cond (fd
616                     (push fd *close-in-parent*)
617                     (values fd nil))
618                    (t
619                     (error "could not duplicate file descriptor: ~S"
620                            (sb-unix:get-unix-error-msg errno)))))))
621         ((sb-sys:fd-stream-p object)
622          (values (sb-sys:fd-stream-fd object) nil))
623         ((streamp object)
624          (ecase direction
625            (:input
626             ;; FIXME: We could use a better way of setting up
627             ;; temporary files, both here and in LOAD-FOREIGN.
628             (dotimes (count
629                        256
630                       (error "could not open a temporary file in /tmp"))
631               (let* ((name (format nil "/tmp/.run-program-~D" count))
632                      (fd (sb-unix:unix-open name
633                                             (logior sb-unix:o_rdwr
634                                                     sb-unix:o_creat
635                                                     sb-unix:o_excl)
636                                             #o666)))
637                 (sb-unix:unix-unlink name)
638                 (when fd
639                   (let ((newline (string #\Newline)))
640                     (loop
641                         (multiple-value-bind
642                               (line no-cr)
643                             (read-line object nil nil)
644                           (unless line
645                             (return))
646                           (sb-unix:unix-write fd line 0 (length line))
647                           (if no-cr
648                               (return)
649                               (sb-unix:unix-write fd newline 0 1)))))
650                   (sb-unix:unix-lseek fd 0 sb-unix:l_set)
651                   (push fd *close-in-parent*)
652                   (return (values fd nil))))))
653            (:output
654             (multiple-value-bind (read-fd write-fd)
655                 (sb-unix:unix-pipe)
656               (unless read-fd
657                 (error "could not create pipe: ~S"
658                        (sb-unix:get-unix-error-msg write-fd)))
659               (copy-descriptor-to-stream read-fd object cookie)
660               (push read-fd *close-on-error*)
661               (push write-fd *close-in-parent*)
662               (values write-fd nil)))))
663         (t
664          (error "invalid option to RUN-PROGRAM: ~S" object))))