1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
4 ;;;; This software is part of the SBCL system. See the README file for
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.
13 (in-package "SB-IMPL") ;(SB-IMPL, not SB!IMPL, since we're built in warm load.)
15 ;;;; hacking the Unix environment
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.
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.
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)))
53 ;;; Convert as best we can from an SBCL representation of a Unix
54 ;;; environment to a CMU CL representation.
56 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
58 ;;; smashing case of "Bletch=fub" in conversion to CMU-CL-style
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)
66 (declare (type simple-base-string string))
67 (let ((=-pos (position #\= string :test #'equal)))
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 ~
79 (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
83 ;;; Convert from a CMU CL representation of a Unix environment to a
84 ;;; SBCL representation.
85 (defun unix-environment-sbcl-from-cmucl (cmucl)
88 (destructuring-bind (key . val) cons
89 (declare (type keyword key) (type simple-base-string val))
90 (concatenate 'simple-base-string (symbol-name key) "=" val)))
93 ;;;; Import wait3(2) from Unix.
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))
100 (defun wait3 (&optional do-not-hang check-for-stopped)
102 "Return any available status information on child process. "
103 (multiple-value-bind (pid status)
104 (c-wait3 (logior (if do-not-hang
107 (if check-for-stopped
111 (cond ((or (minusp pid)
114 ((eql (ldb (byte 8 0) status)
118 (ldb (byte 8 8) status)))
119 ((zerop (ldb (byte 7 0) status))
122 (ldb (byte 8 8) status)))
124 (let ((signal (ldb (byte 7 0) status)))
135 (not (zerop (ldb (byte 1 7) status)))))))))
137 ;;;; process control stuff
139 (defvar *active-processes* nil
141 "List of process structures for all active processes.")
143 (defvar *active-processes-lock*
144 (sb-thread:make-mutex :name "Lock for active processes."))
146 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
147 ;;; mutex is needed. More importantly the sigchld signal handler also
148 ;;; accesses it, that's why we need without-interrupts.
149 (defmacro with-active-processes-lock (() &body body)
151 (sb-thread:with-mutex (*active-processes-lock*)
154 (defstruct (process (:copier nil))
155 pid ; PID of child process
156 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
157 exit-code ; either exit code or signal
158 core-dumped ; T if a core image was dumped
159 pty ; stream to child's pty, or NIL
160 input ; stream to child's input, or NIL
161 output ; stream from child's output, or NIL
162 error ; stream from child's error output, or NIL
163 status-hook ; closure to call when PROC changes status
164 plist ; a place for clients to stash things
165 cookie) ; list of the number of pipes from the subproc
169 (defmethod print-object ((process process) stream)
170 (print-unreadable-object (process stream :type t)
173 (process-pid process)
174 (process-status process)))
178 (setf (documentation 'process-p 'function)
179 "T if OBJECT is a PROCESS, NIL otherwise.")
182 (setf (documentation 'process-pid 'function) "The pid of the child process.")
184 (defun process-status (process)
186 "Return the current status of PROCESS. The result is one of :RUNNING,
187 :STOPPED, :EXITED, or :SIGNALED."
188 (get-processes-status-changes)
189 (process-%status process))
192 (setf (documentation 'process-exit-code 'function)
193 "The exit code or the signal of a stopped process.")
196 (setf (documentation 'process-core-dumped 'function)
197 "T if a core image was dumped by the process.")
200 (setf (documentation 'process-pty 'function)
201 "The pty stream of the process or NIL.")
204 (setf (documentation 'process-input 'function)
205 "The input stream of the process or NIL.")
208 (setf (documentation 'process-output 'function)
209 "The output stream of the process or NIL.")
212 (setf (documentation 'process-error 'function)
213 "The error stream of the process or NIL.")
216 (setf (documentation 'process-status-hook 'function)
217 "A function that is called when PROCESS changes its status.
218 The function is called with PROCESS as its only argument.")
221 (setf (documentation 'process-plist 'function)
222 "A place for clients to stash things.")
224 (defun process-wait (process &optional check-for-stopped)
226 "Wait for PROCESS to quit running for some reason.
227 When CHECK-FOR-STOPPED is T, also returns when PROCESS is
228 stopped. Returns PROCESS."
230 (case (process-status process)
233 (when check-for-stopped
236 (when (zerop (car (process-cookie process)))
238 (sb-sys:serve-all-events 1))
242 ;;; Find the current foreground process group id.
243 (defun find-current-foreground-process (proc)
244 (with-alien ((result sb-alien:int))
247 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
249 (alien-sap (sb-alien:addr result)))
251 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
255 (defun process-kill (process signal &optional (whom :pid))
257 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
258 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
259 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
260 currently in the foreground."
261 (let ((pid (ecase whom
262 ((:pid :process-group)
263 (process-pid process))
266 (find-current-foreground-process process)))))
272 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty process))
276 ((:process-group #-hpux :pty-process-group)
277 (sb-unix:unix-killpg pid signal))
279 (sb-unix:unix-kill pid signal)))
282 ((and (eql pid (process-pid process))
283 (= signal sb-unix:sigcont))
284 (setf (process-%status process) :running)
285 (setf (process-exit-code process) nil)
286 (when (process-status-hook process)
287 (funcall (process-status-hook process) process))
292 (defun process-alive-p (process)
294 "Return T if PROCESS is still alive, NIL otherwise."
295 (let ((status (process-status process)))
296 (if (or (eq status :running)
297 (eq status :stopped))
301 (defun process-close (process)
303 "Close all streams connected to PROCESS and stop maintaining the status slot."
304 (macrolet ((frob (stream abort)
305 `(when ,stream (close ,stream :abort ,abort))))
306 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process, ..
307 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
308 (frob (process-output process) nil)
309 (frob (process-error process) nil))
310 (with-active-processes-lock ()
311 (setf *active-processes* (delete process *active-processes*)))
314 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
315 (defun sigchld-handler (ignore1 ignore2 ignore3)
316 (declare (ignore ignore1 ignore2 ignore3))
317 (get-processes-status-changes))
319 (defun get-processes-status-changes ()
321 (multiple-value-bind (pid what code core)
325 (let ((proc (with-active-processes-lock ()
326 (find pid *active-processes* :key #'process-pid))))
328 (setf (process-%status proc) what)
329 (setf (process-exit-code proc) code)
330 (setf (process-core-dumped proc) core)
331 (when (process-status-hook proc)
332 (funcall (process-status-hook proc) proc))
333 (when (position what #(:exited :signaled))
334 (with-active-processes-lock ()
335 (setf *active-processes*
336 (delete proc *active-processes*)))))))))
338 ;;;; RUN-PROGRAM and close friends
340 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
341 (defvar *close-on-error* nil)
343 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
344 (defvar *close-in-parent* nil)
346 ;;; list of handlers installed by RUN-PROGRAM
347 (defvar *handlers-installed* nil)
349 ;;; Find an unused pty. Return three values: the file descriptor for
350 ;;; the master side of the pty, the file descriptor for the slave side
351 ;;; of the pty, and the name of the tty device for the slave side.
353 (dolist (char '(#\p #\q))
355 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit) 'base-string))
356 (master-fd (sb-unix:unix-open master-name
360 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit) 'base-string))
361 (slave-fd (sb-unix:unix-open slave-name
365 (return-from find-a-pty
369 (sb-unix:unix-close master-fd))))))
370 (error "could not find a pty"))
372 (defun open-pty (pty cookie)
377 (push master *close-on-error*)
378 (push slave *close-in-parent*)
380 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
382 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
383 (push new-fd *close-on-error*)
384 (copy-descriptor-to-stream new-fd pty cookie)))
386 (sb-sys:make-fd-stream master :input t :output t
387 :element-type :default
388 :dual-channel-p t)))))
390 (defmacro round-bytes-to-words (n)
391 `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
393 (defun string-list-to-c-strvec (string-list)
394 ;; Make a pass over STRING-LIST to calculate the amount of memory
395 ;; needed to hold the strvec.
396 (let ((string-bytes 0)
397 ;; We need an extra for the null, and an extra 'cause exect
398 ;; clobbers argv[-1].
399 (vec-bytes (* #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)
400 (+ (length string-list) 2))))
401 (declare (fixnum string-bytes vec-bytes))
402 (dolist (s string-list)
403 (enforce-type s simple-string)
404 (incf string-bytes (round-bytes-to-words (1+ (length s)))))
405 ;; Now allocate the memory and fill it in.
406 (let* ((total-bytes (+ string-bytes vec-bytes))
407 (vec-sap (sb-sys:allocate-system-memory total-bytes))
408 (string-sap (sap+ vec-sap vec-bytes))
409 (i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)))
410 (declare (type (and unsigned-byte fixnum) total-bytes i)
411 (type sb-sys:system-area-pointer vec-sap string-sap))
412 (dolist (s string-list)
413 (declare (simple-string s))
414 (let ((n (length s)))
415 ;; Blast the string into place.
416 (sb-kernel:copy-ub8-to-system-area (the simple-base-string
418 (coerce s 'simple-base-string))
422 ;; Blast the pointer to the string into place.
423 (setf (sap-ref-sap vec-sap i) string-sap)
424 (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
425 (incf i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits))))
426 ;; Blast in the last null pointer.
427 (setf (sap-ref-sap vec-sap i) (int-sap 0))
428 (values vec-sap (sap+ vec-sap #.(/ sb-vm::n-machine-word-bits
432 (defmacro with-c-strvec ((var str-list) &body body)
433 (with-unique-names (sap size)
434 `(multiple-value-bind
436 (string-list-to-c-strvec ,str-list)
440 (sb-sys:deallocate-system-memory ,sap ,size)))))
442 (sb-alien:define-alien-routine spawn sb-alien:int
443 (program sb-alien:c-string)
444 (argv (* sb-alien:c-string))
445 (envp (* sb-alien:c-string))
446 (pty-name sb-alien:c-string)
448 (stdout sb-alien:int)
449 (stderr sb-alien:int))
451 ;;; Is UNIX-FILENAME the name of a file that we can execute?
452 (defun unix-filename-is-executable-p (unix-filename)
453 (declare (type simple-string unix-filename))
454 (setf unix-filename (coerce unix-filename 'base-string))
455 (values (and (eq (sb-unix:unix-file-kind unix-filename) :file)
456 (sb-unix:unix-access unix-filename sb-unix:x_ok))))
458 (defun find-executable-in-search-path (pathname
460 (search-path (posix-getenv "PATH")))
462 "Find the first executable file matching PATHNAME in any of the
463 colon-separated list of pathnames SEARCH-PATH"
464 (loop for end = (position #\: search-path :start (if end (1+ end) 0))
465 and start = 0 then (and end (1+ end))
467 ;; <Krystof> the truename of a file naming a directory is the
468 ;; directory, at least until pfdietz comes along and says why
469 ;; that's noncompliant -- CSR, c. 2003-08-10
470 for truename = (probe-file (subseq search-path start end))
471 for fullpath = (when truename (merge-pathnames pathname truename))
473 (unix-filename-is-executable-p (namestring fullpath)))
476 ;;; FIXME: There shouldn't be two semiredundant versions of the
477 ;;; documentation. Since this is a public extension function, the
478 ;;; documentation should be in the doc string. So all information from
479 ;;; this comment should be merged into the doc string, and then this
480 ;;; comment can go away.
482 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
483 ;;; Strange stuff happens to keep the Unix state of the world
486 ;;; The child process needs to get its input from somewhere, and send
487 ;;; its output (both standard and error) to somewhere. We have to do
488 ;;; different things depending on where these somewheres really are.
490 ;;; For input, there are five options:
491 ;;; -- T: Just leave fd 0 alone. Pretty simple.
492 ;;; -- "file": Read from the file. We need to open the file and
493 ;;; pull the descriptor out of the stream. The parent should close
494 ;;; this stream after the child is up and running to free any
495 ;;; storage used in the parent.
496 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
497 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
498 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
499 ;;; writeable descriptor, and pass the readable descriptor to
500 ;;; the child. The parent must close the readable descriptor for
501 ;;; EOF to be passed up correctly.
502 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
503 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
504 ;;; everything across.
506 ;;; For output, there are five options:
507 ;;; -- T: Leave descriptor 1 alone.
508 ;;; -- "file": dump output to the file.
509 ;;; -- NIL: dump output to /dev/null.
510 ;;; -- :STREAM: return a stream that can be read from.
511 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
512 ;;; Otherwise, copy stuff from output to stream.
514 ;;; For error, there are all the same options as output plus:
515 ;;; -- :OUTPUT: redirect to the same place as output.
517 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
518 ;;; the fork worked, and NIL if it did not.
519 (defun run-program (program args
522 (environment (if env-p
523 (unix-environment-sbcl-from-cmucl env)
530 if-input-does-not-exist
532 (if-output-exists :error)
534 (if-error-exists :error)
537 "RUN-PROGRAM creates a new Unix process running the Unix program found in
538 the file specified by the PROGRAM argument. ARGS are the standard
539 arguments that can be passed to a Unix program. For no arguments, use NIL
540 (which means that just the name of the program is passed as arg 0).
542 RUN-PROGRAM will return a PROCESS structure or NIL on failure.
543 See the CMU Common Lisp Users Manual for details about the
546 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
548 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
549 programs, but unlike the original CMU CL implementation, copies
550 the Unix environment by default.
552 - Running Unix programs from a setuid process, or in any other
553 situation where the Unix environment is under the control of someone
554 else, is a mother lode of security problems. If you are contemplating
555 doing this, read about it first. (The Perl community has a lot of good
556 documentation about this and other security issues in script-like
559 The &KEY arguments have the following meanings:
562 a list of SIMPLE-BASE-STRINGs describing the new Unix environment
563 (as in \"man environ\"). The default is to copy the environment of
566 an alternative lossy representation of the new Unix environment,
567 for compatibility with CMU CL
569 Look for PROGRAM in each of the directories along the $PATH
570 environment variable. Otherwise an absolute pathname is required.
571 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
573 If non-NIL (default), wait until the created process finishes. If
574 NIL, continue running Lisp until the program finishes.
576 Either T, NIL, or a stream. Unless NIL, the subprocess is established
577 under a PTY. If :pty is a stream, all output to this pty is sent to
578 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
579 connected to pty that can read output and write input.
581 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
582 input for the current process is inherited. If NIL, /dev/null
583 is used. If a pathname, the file so specified is used. If a stream,
584 all the input is read from that stream and send to the subprocess. If
585 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
586 its output to the process. Defaults to NIL.
587 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
589 :ERROR to generate an error
590 :CREATE to create an empty file
591 NIL (the default) to return NIL from RUN-PROGRAM
593 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
594 output for the current process is inherited. If NIL, /dev/null
595 is used. If a pathname, the file so specified is used. If a stream,
596 all the output from the process is written to this stream. If
597 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
598 be read to get the output. Defaults to NIL.
599 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
601 :ERROR (the default) to generate an error
602 :SUPERSEDE to supersede the file with output from the program
603 :APPEND to append output from the program to the file
604 NIL to return NIL from RUN-PROGRAM, without doing anything
605 :ERROR and :IF-ERROR-EXISTS
606 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
607 specified as :OUTPUT in which case all error output is routed to the
608 same place as normal output.
610 This is a function the system calls whenever the status of the
611 process changes. The function takes the process as an argument."
613 (when (and env-p environment-p)
614 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
615 ;; Make sure that the interrupt handler is installed.
616 (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
617 ;; Prepend the program to the argument list.
618 (push (namestring program) args)
619 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
620 ;; communicate cleanup info.
624 ;; Establish PROC at this level so that we can return it.
626 ;; It's friendly to allow the caller to pass any string
627 ;; designator, but internally we'd like SIMPLE-STRINGs.
628 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
632 (let ((p (find-executable-in-search-path program)))
633 (and p (unix-namestring p t)))
634 (unix-namestring program t)))
637 (error "no such program: ~S" program))
638 (unless (unix-filename-is-executable-p pfile)
639 (error "not executable: ~S" program))
640 (multiple-value-bind (stdin input-stream)
641 (get-descriptor-for input cookie
643 :if-does-not-exist if-input-does-not-exist)
644 (multiple-value-bind (stdout output-stream)
645 (get-descriptor-for output cookie
647 :if-exists if-output-exists)
648 (multiple-value-bind (stderr error-stream)
649 (if (eq error :output)
650 (values stdout output-stream)
651 (get-descriptor-for error cookie
653 :if-exists if-error-exists))
654 (multiple-value-bind (pty-name pty-stream)
655 (open-pty pty cookie)
656 ;; Make sure we are not notified about the child
657 ;; death before we have installed the PROCESS
658 ;; structure in *ACTIVE-PROCESSES*.
659 (with-active-processes-lock ()
660 (with-c-strvec (args-vec simple-args)
661 (with-c-strvec (environment-vec environment)
664 (spawn pfile args-vec environment-vec pty-name
665 stdin stdout stderr))))
666 (when (< child-pid 0)
667 (error "couldn't fork child process: ~A"
669 (setf proc (make-process :pid child-pid
673 :output output-stream
675 :status-hook status-hook
677 (push proc *active-processes*))))))))))
678 (dolist (fd *close-in-parent*)
679 (sb-unix:unix-close fd))
681 (dolist (fd *close-on-error*)
682 (sb-unix:unix-close fd))
683 (dolist (handler *handlers-installed*)
684 (sb-sys:remove-fd-handler handler))))
685 (when (and wait proc)
689 ;;; Install a handler for any input that shows up on the file
690 ;;; descriptor. The handler reads the data and writes it to the
692 (defun copy-descriptor-to-stream (descriptor stream cookie)
694 (let ((string (make-string 256 :element-type 'base-char))
697 (sb-sys:add-fd-handler
700 (declare (ignore fd))
705 (result readable/errno)
706 (sb-unix:unix-select (1+ descriptor)
710 (error "~@<couldn't select on sub-process: ~
712 (strerror readable/errno)))
715 (sb-alien:with-alien ((buf (sb-alien:array
720 (sb-unix:unix-read descriptor
723 (cond ((or (and (null count)
724 (eql errno sb-unix:eio))
726 (sb-sys:remove-fd-handler handler)
729 (sb-unix:unix-close descriptor)
732 (sb-sys:remove-fd-handler handler)
736 "~@<couldn't read input from sub-process: ~
740 (sb-kernel:copy-ub8-from-system-area
744 (write-string string stream
745 :end count)))))))))))
747 ;;; Find a file descriptor to use for object given the direction.
748 ;;; Returns the descriptor. If object is :STREAM, returns the created
749 ;;; stream as the second value.
750 (defun get-descriptor-for (object
756 ;; No new descriptor is needed.
762 (sb-unix:unix-open #.(coerce "/dev/null" 'base-string)
764 (:input sb-unix:o_rdonly)
765 (:output sb-unix:o_wronly)
769 (error "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
771 (push fd *close-in-parent*)
774 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
776 (error "couldn't create pipe: ~A" (strerror write-fd)))
779 (push read-fd *close-in-parent*)
780 (push write-fd *close-on-error*)
781 (let ((stream (sb-sys:make-fd-stream write-fd :output t
782 :element-type :default)))
783 (values read-fd stream)))
785 (push read-fd *close-on-error*)
786 (push write-fd *close-in-parent*)
787 (let ((stream (sb-sys:make-fd-stream read-fd :input t
788 :element-type :default)))
789 (values write-fd stream)))
791 (sb-unix:unix-close read-fd)
792 (sb-unix:unix-close write-fd)
793 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
795 ((or (pathnamep object) (stringp object))
796 (with-open-stream (file (apply #'open object keys))
799 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
801 (push fd *close-in-parent*)
804 (error "couldn't duplicate file descriptor: ~A"
805 (strerror errno)))))))
806 ((sb-sys:fd-stream-p object)
807 (values (sb-sys:fd-stream-fd object) nil))
811 ;; FIXME: We could use a better way of setting up
812 ;; temporary files, both here and in LOAD-FOREIGN.
815 (error "could not open a temporary file in /tmp"))
816 (let* ((name (coerce (format nil "/tmp/.run-program-~D" count) 'base-string))
817 (fd (sb-unix:unix-open name
818 (logior sb-unix:o_rdwr
822 (sb-unix:unix-unlink name)
824 (let ((newline (string #\Newline)))
828 (read-line object nil nil)
833 ;; FIXME: this really should be
834 ;; (STRING-TO-OCTETS :EXTERNAL-FORMAT ...).
835 ;; RUN-PROGRAM should take an
836 ;; external-format argument, which should
837 ;; be passed down to here. Something
838 ;; similar should happen on :OUTPUT, too.
839 (map '(vector (unsigned-byte 8)) #'char-code line)
843 (sb-unix:unix-write fd newline 0 1)))))
844 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
845 (push fd *close-in-parent*)
846 (return (values fd nil))))))
848 (multiple-value-bind (read-fd write-fd)
851 (error "couldn't create pipe: ~S" (strerror write-fd)))
852 (copy-descriptor-to-stream read-fd object cookie)
853 (push read-fd *close-on-error*)
854 (push write-fd *close-in-parent*)
855 (values write-fd nil)))))
857 (error "invalid option to RUN-PROGRAM: ~S" object))))