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 :dual-channel-p t)))))
389 (defmacro round-bytes-to-words (n)
390 `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
392 (defun string-list-to-c-strvec (string-list)
393 ;; Make a pass over STRING-LIST to calculate the amount of memory
394 ;; needed to hold the strvec.
395 (let ((string-bytes 0)
396 ;; We need an extra for the null, and an extra 'cause exect
397 ;; clobbers argv[-1].
398 (vec-bytes (* #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)
399 (+ (length string-list) 2))))
400 (declare (fixnum string-bytes vec-bytes))
401 (dolist (s string-list)
402 (enforce-type s simple-string)
403 (incf string-bytes (round-bytes-to-words (1+ (length s)))))
404 ;; Now allocate the memory and fill it in.
405 (let* ((total-bytes (+ string-bytes vec-bytes))
406 (vec-sap (sb-sys:allocate-system-memory total-bytes))
407 (string-sap (sap+ vec-sap vec-bytes))
408 (i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)))
409 (declare (type (and unsigned-byte fixnum) total-bytes i)
410 (type sb-sys:system-area-pointer vec-sap string-sap))
411 (dolist (s string-list)
412 (declare (simple-string s))
413 (let ((n (length s)))
414 ;; Blast the string into place.
415 (sb-kernel:copy-ub8-to-system-area (the simple-base-string
417 (coerce s 'simple-base-string))
421 ;; Blast the pointer to the string into place.
422 (setf (sap-ref-sap vec-sap i) string-sap)
423 (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
424 (incf i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits))))
425 ;; Blast in the last null pointer.
426 (setf (sap-ref-sap vec-sap i) (int-sap 0))
427 (values vec-sap (sap+ vec-sap #.(/ sb-vm::n-machine-word-bits
431 (defmacro with-c-strvec ((var str-list) &body body)
432 (with-unique-names (sap size)
433 `(multiple-value-bind
435 (string-list-to-c-strvec ,str-list)
439 (sb-sys:deallocate-system-memory ,sap ,size)))))
441 (sb-alien:define-alien-routine spawn sb-alien:int
442 (program sb-alien:c-string)
443 (argv (* sb-alien:c-string))
444 (envp (* sb-alien:c-string))
445 (pty-name sb-alien:c-string)
447 (stdout sb-alien:int)
448 (stderr sb-alien:int))
450 ;;; Is UNIX-FILENAME the name of a file that we can execute?
451 (defun unix-filename-is-executable-p (unix-filename)
452 (declare (type simple-string unix-filename))
453 (setf unix-filename (coerce unix-filename 'base-string))
454 (values (and (eq (sb-unix:unix-file-kind unix-filename) :file)
455 (sb-unix:unix-access unix-filename sb-unix:x_ok))))
457 (defun find-executable-in-search-path (pathname
459 (search-path (posix-getenv "PATH")))
461 "Find the first executable file matching PATHNAME in any of the
462 colon-separated list of pathnames SEARCH-PATH"
463 (loop for end = (position #\: search-path :start (if end (1+ end) 0))
464 and start = 0 then (and end (1+ end))
466 ;; <Krystof> the truename of a file naming a directory is the
467 ;; directory, at least until pfdietz comes along and says why
468 ;; that's noncompliant -- CSR, c. 2003-08-10
469 for truename = (probe-file (subseq search-path start end))
470 for fullpath = (when truename (merge-pathnames pathname truename))
472 (unix-filename-is-executable-p (namestring fullpath)))
475 ;;; FIXME: There shouldn't be two semiredundant versions of the
476 ;;; documentation. Since this is a public extension function, the
477 ;;; documentation should be in the doc string. So all information from
478 ;;; this comment should be merged into the doc string, and then this
479 ;;; comment can go away.
481 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
482 ;;; Strange stuff happens to keep the Unix state of the world
485 ;;; The child process needs to get its input from somewhere, and send
486 ;;; its output (both standard and error) to somewhere. We have to do
487 ;;; different things depending on where these somewheres really are.
489 ;;; For input, there are five options:
490 ;;; -- T: Just leave fd 0 alone. Pretty simple.
491 ;;; -- "file": Read from the file. We need to open the file and
492 ;;; pull the descriptor out of the stream. The parent should close
493 ;;; this stream after the child is up and running to free any
494 ;;; storage used in the parent.
495 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
496 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
497 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
498 ;;; writeable descriptor, and pass the readable descriptor to
499 ;;; the child. The parent must close the readable descriptor for
500 ;;; EOF to be passed up correctly.
501 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
502 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
503 ;;; everything across.
505 ;;; For output, there are five options:
506 ;;; -- T: Leave descriptor 1 alone.
507 ;;; -- "file": dump output to the file.
508 ;;; -- NIL: dump output to /dev/null.
509 ;;; -- :STREAM: return a stream that can be read from.
510 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
511 ;;; Otherwise, copy stuff from output to stream.
513 ;;; For error, there are all the same options as output plus:
514 ;;; -- :OUTPUT: redirect to the same place as output.
516 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
517 ;;; the fork worked, and NIL if it did not.
518 (defun run-program (program args
521 (environment (if env-p
522 (unix-environment-sbcl-from-cmucl env)
529 if-input-does-not-exist
531 (if-output-exists :error)
533 (if-error-exists :error)
536 "RUN-PROGRAM creates a new Unix process running the Unix program found in
537 the file specified by the PROGRAM argument. ARGS are the standard
538 arguments that can be passed to a Unix program. For no arguments, use NIL
539 (which means that just the name of the program is passed as arg 0).
541 RUN-PROGRAM will return a PROCESS structure or NIL on failure.
542 See the CMU Common Lisp Users Manual for details about the
545 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
547 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
548 programs, but unlike the original CMU CL implementation, copies
549 the Unix environment by default.
551 - Running Unix programs from a setuid process, or in any other
552 situation where the Unix environment is under the control of someone
553 else, is a mother lode of security problems. If you are contemplating
554 doing this, read about it first. (The Perl community has a lot of good
555 documentation about this and other security issues in script-like
558 The &KEY arguments have the following meanings:
561 a list of SIMPLE-BASE-STRINGs describing the new Unix environment
562 (as in \"man environ\"). The default is to copy the environment of
565 an alternative lossy representation of the new Unix environment,
566 for compatibility with CMU CL
568 Look for PROGRAM in each of the directories along the $PATH
569 environment variable. Otherwise an absolute pathname is required.
570 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
572 If non-NIL (default), wait until the created process finishes. If
573 NIL, continue running Lisp until the program finishes.
575 Either T, NIL, or a stream. Unless NIL, the subprocess is established
576 under a PTY. If :pty is a stream, all output to this pty is sent to
577 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
578 connected to pty that can read output and write input.
580 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
581 input for the current process is inherited. If NIL, /dev/null
582 is used. If a pathname, the file so specified is used. If a stream,
583 all the input is read from that stream and send to the subprocess. If
584 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
585 its output to the process. Defaults to NIL.
586 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
588 :ERROR to generate an error
589 :CREATE to create an empty file
590 NIL (the default) to return NIL from RUN-PROGRAM
592 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
593 output for the current process is inherited. If NIL, /dev/null
594 is used. If a pathname, the file so specified is used. If a stream,
595 all the output from the process is written to this stream. If
596 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
597 be read to get the output. Defaults to NIL.
598 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
600 :ERROR (the default) to generate an error
601 :SUPERSEDE to supersede the file with output from the program
602 :APPEND to append output from the program to the file
603 NIL to return NIL from RUN-PROGRAM, without doing anything
604 :ERROR and :IF-ERROR-EXISTS
605 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
606 specified as :OUTPUT in which case all error output is routed to the
607 same place as normal output.
609 This is a function the system calls whenever the status of the
610 process changes. The function takes the process as an argument."
612 (when (and env-p environment-p)
613 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
614 ;; Make sure that the interrupt handler is installed.
615 (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
616 ;; Prepend the program to the argument list.
617 (push (namestring program) args)
618 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
619 ;; communicate cleanup info.
623 ;; Establish PROC at this level so that we can return it.
625 ;; It's friendly to allow the caller to pass any string
626 ;; designator, but internally we'd like SIMPLE-STRINGs.
627 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
631 (let ((p (find-executable-in-search-path program)))
632 (and p (unix-namestring p t)))
633 (unix-namestring program t)))
636 (error "no such program: ~S" program))
637 (unless (unix-filename-is-executable-p pfile)
638 (error "not executable: ~S" program))
639 (multiple-value-bind (stdin input-stream)
640 (get-descriptor-for input cookie
642 :if-does-not-exist if-input-does-not-exist)
643 (multiple-value-bind (stdout output-stream)
644 (get-descriptor-for output cookie
646 :if-exists if-output-exists)
647 (multiple-value-bind (stderr error-stream)
648 (if (eq error :output)
649 (values stdout output-stream)
650 (get-descriptor-for error cookie
652 :if-exists if-error-exists))
653 (multiple-value-bind (pty-name pty-stream)
654 (open-pty pty cookie)
655 ;; Make sure we are not notified about the child
656 ;; death before we have installed the PROCESS
657 ;; structure in *ACTIVE-PROCESSES*.
658 (with-active-processes-lock ()
659 (with-c-strvec (args-vec simple-args)
660 (with-c-strvec (environment-vec environment)
663 (spawn pfile args-vec environment-vec pty-name
664 stdin stdout stderr))))
665 (when (< child-pid 0)
666 (error "couldn't fork child process: ~A"
668 (setf proc (make-process :pid child-pid
672 :output output-stream
674 :status-hook status-hook
676 (push proc *active-processes*))))))))))
677 (dolist (fd *close-in-parent*)
678 (sb-unix:unix-close fd))
680 (dolist (fd *close-on-error*)
681 (sb-unix:unix-close fd))
682 (dolist (handler *handlers-installed*)
683 (sb-sys:remove-fd-handler handler))))
684 (when (and wait proc)
688 ;;; Install a handler for any input that shows up on the file
689 ;;; descriptor. The handler reads the data and writes it to the
691 (defun copy-descriptor-to-stream (descriptor stream cookie)
693 (let ((string (make-string 256 :element-type 'base-char))
696 (sb-sys:add-fd-handler
699 (declare (ignore fd))
704 (result readable/errno)
705 (sb-unix:unix-select (1+ descriptor)
709 (error "~@<couldn't select on sub-process: ~
711 (strerror readable/errno)))
714 (sb-alien:with-alien ((buf (sb-alien:array
719 (sb-unix:unix-read descriptor
722 (cond ((or (and (null count)
723 (eql errno sb-unix:eio))
725 (sb-sys:remove-fd-handler handler)
728 (sb-unix:unix-close descriptor)
731 (sb-sys:remove-fd-handler handler)
735 "~@<couldn't read input from sub-process: ~
739 (sb-kernel:copy-ub8-from-system-area
743 (write-string string stream
744 :end count)))))))))))
746 ;;; Find a file descriptor to use for object given the direction.
747 ;;; Returns the descriptor. If object is :STREAM, returns the created
748 ;;; stream as the second value.
749 (defun get-descriptor-for (object
755 ;; No new descriptor is needed.
761 (sb-unix:unix-open #.(coerce "/dev/null" 'base-string)
763 (:input sb-unix:o_rdonly)
764 (:output sb-unix:o_wronly)
768 (error "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
770 (push fd *close-in-parent*)
773 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
775 (error "couldn't create pipe: ~A" (strerror write-fd)))
778 (push read-fd *close-in-parent*)
779 (push write-fd *close-on-error*)
780 (let ((stream (sb-sys:make-fd-stream write-fd :output t)))
781 (values read-fd stream)))
783 (push read-fd *close-on-error*)
784 (push write-fd *close-in-parent*)
785 (let ((stream (sb-sys:make-fd-stream read-fd :input t)))
786 (values write-fd stream)))
788 (sb-unix:unix-close read-fd)
789 (sb-unix:unix-close write-fd)
790 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
792 ((or (pathnamep object) (stringp object))
793 (with-open-stream (file (apply #'open object keys))
796 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
798 (push fd *close-in-parent*)
801 (error "couldn't duplicate file descriptor: ~A"
802 (strerror errno)))))))
803 ((sb-sys:fd-stream-p object)
804 (values (sb-sys:fd-stream-fd object) nil))
808 ;; FIXME: We could use a better way of setting up
809 ;; temporary files, both here and in LOAD-FOREIGN.
812 (error "could not open a temporary file in /tmp"))
813 (let* ((name (coerce (format nil "/tmp/.run-program-~D" count) 'base-string))
814 (fd (sb-unix:unix-open name
815 (logior sb-unix:o_rdwr
819 (sb-unix:unix-unlink name)
821 (let ((newline (string #\Newline)))
825 (read-line object nil nil)
830 ;; FIXME: this really should be
831 ;; (STRING-TO-OCTETS :EXTERNAL-FORMAT ...).
832 ;; RUN-PROGRAM should take an
833 ;; external-format argument, which should
834 ;; be passed down to here. Something
835 ;; similar should happen on :OUTPUT, too.
836 (map '(vector (unsigned-byte 8)) #'char-code line)
840 (sb-unix:unix-write fd newline 0 1)))))
841 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
842 (push fd *close-in-parent*)
843 (return (values fd nil))))))
845 (multiple-value-bind (read-fd write-fd)
848 (error "couldn't create pipe: ~S" (strerror write-fd)))
849 (copy-descriptor-to-stream read-fd object cookie)
850 (push read-fd *close-on-error*)
851 (push write-fd *close-in-parent*)
852 (values write-fd nil)))))
854 (error "invalid option to RUN-PROGRAM: ~S" object))))