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.
50 (define-alien-routine wrapped-environ (* c-string))
51 (defun posix-environ ()
52 "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
53 (c-strings->string-list (wrapped-environ))))
55 ;#+win32 (sb-alien:define-alien-routine msvcrt-environ (* c-string))
57 ;;; Convert as best we can from an SBCL representation of a Unix
58 ;;; environment to a CMU CL representation.
60 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
62 ;;; smashing case of "Bletch=fub" in conversion to CMU-CL-style
65 ;;; no #\= in "Noggin", eliding it in CMU-CL-style environment alist
66 ;;; ((:BLETCH . "fub") (:YES . "No!"))
67 (defun unix-environment-cmucl-from-sbcl (sbcl)
70 (declare (string string))
71 (let ((=-pos (position #\= string :test #'equal)))
74 (let* ((key-as-string (subseq string 0 =-pos))
75 (key-as-upcase-string (string-upcase key-as-string))
76 (key (keywordicate key-as-upcase-string))
77 (val (subseq string (1+ =-pos))))
78 (unless (string= key-as-string key-as-upcase-string)
79 (warn "smashing case of ~S in conversion to CMU-CL-style ~
83 (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
87 ;;; Convert from a CMU CL representation of a Unix environment to a
88 ;;; SBCL representation.
89 (defun unix-environment-sbcl-from-cmucl (cmucl)
92 (destructuring-bind (key . val) cons
93 (declare (type keyword key) (string val))
94 (concatenate 'simple-string (symbol-name key) "=" val)))
97 ;;;; Import wait3(2) from Unix.
100 (define-alien-routine ("wait3" c-wait3) sb-alien:int
101 (status sb-alien:int :out)
102 (options sb-alien:int)
103 (rusage sb-alien:int))
106 (defun wait3 (&optional do-not-hang check-for-stopped)
108 "Return any available status information on child process. "
109 (multiple-value-bind (pid status)
110 (c-wait3 (logior (if do-not-hang
113 (if check-for-stopped
117 (cond ((or (minusp pid)
120 ((eql (ldb (byte 8 0) status)
124 (ldb (byte 8 8) status)))
125 ((zerop (ldb (byte 7 0) status))
128 (ldb (byte 8 8) status)))
130 (let ((signal (ldb (byte 7 0) status)))
141 (not (zerop (ldb (byte 1 7) status)))))))))
143 ;;;; process control stuff
144 (defvar *active-processes* nil
146 "List of process structures for all active processes.")
149 (defvar *active-processes-lock*
150 (sb-thread:make-mutex :name "Lock for active processes."))
152 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
153 ;;; mutex is needed. More importantly the sigchld signal handler also
154 ;;; accesses it, that's why we need without-interrupts.
155 (defmacro with-active-processes-lock (() &body body)
157 `(sb-thread::with-system-mutex (*active-processes-lock* :allow-with-interrupts t)
162 (defstruct (process (:copier nil))
163 pid ; PID of child process
164 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
165 exit-code ; either exit code or signal
166 core-dumped ; T if a core image was dumped
167 #-win32 pty ; stream to child's pty, or NIL
168 input ; stream to child's input, or NIL
169 output ; stream from child's output, or NIL
170 error ; stream from child's error output, or NIL
171 status-hook ; closure to call when PROC changes status
172 plist ; a place for clients to stash things
173 cookie) ; list of the number of pipes from the subproc
175 (defmethod print-object ((process process) stream)
176 (print-unreadable-object (process stream :type t)
177 (let ((status (process-status process)))
178 (if (eq :exited status)
179 (format stream "~S ~S" status (process-exit-code process))
180 (format stream "~S ~S" (process-pid process) status)))
184 (setf (documentation 'process-p 'function)
185 "T if OBJECT is a PROCESS, NIL otherwise.")
188 (setf (documentation 'process-pid 'function) "The pid of the child process.")
191 (define-alien-routine ("GetExitCodeProcess@8" get-exit-code-process)
193 (handle unsigned) (exit-code unsigned :out))
195 (defun process-status (process)
197 "Return the current status of PROCESS. The result is one of :RUNNING,
198 :STOPPED, :EXITED, or :SIGNALED."
199 (get-processes-status-changes)
200 (process-%status process))
203 (setf (documentation 'process-exit-code 'function)
204 "The exit code or the signal of a stopped process.")
207 (setf (documentation 'process-core-dumped 'function)
208 "T if a core image was dumped by the process.")
211 (setf (documentation 'process-pty 'function)
212 "The pty stream of the process or NIL.")
215 (setf (documentation 'process-input 'function)
216 "The input stream of the process or NIL.")
219 (setf (documentation 'process-output 'function)
220 "The output stream of the process or NIL.")
223 (setf (documentation 'process-error 'function)
224 "The error stream of the process or NIL.")
227 (setf (documentation 'process-status-hook 'function)
228 "A function that is called when PROCESS changes its status.
229 The function is called with PROCESS as its only argument.")
232 (setf (documentation 'process-plist 'function)
233 "A place for clients to stash things.")
235 (defun process-wait (process &optional check-for-stopped)
237 "Wait for PROCESS to quit running for some reason. When
238 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
241 (case (process-status process)
244 (when check-for-stopped
247 (when (zerop (car (process-cookie process)))
249 (sb-sys:serve-all-events 1))
253 ;;; Find the current foreground process group id.
254 (defun find-current-foreground-process (proc)
255 (with-alien ((result sb-alien:int))
258 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
260 (alien-sap (sb-alien:addr result)))
262 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
267 (defun process-kill (process signal &optional (whom :pid))
269 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
270 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
271 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
272 currently in the foreground."
273 (let ((pid (ecase whom
274 ((:pid :process-group)
275 (process-pid process))
278 (find-current-foreground-process process)))))
284 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty process))
288 ((:process-group #-hpux :pty-process-group)
289 (sb-unix:unix-killpg pid signal))
291 (sb-unix:unix-kill pid signal)))
294 ((and (eql pid (process-pid process))
295 (= signal sb-unix:sigcont))
296 (setf (process-%status process) :running)
297 (setf (process-exit-code process) nil)
298 (when (process-status-hook process)
299 (funcall (process-status-hook process) process))
304 (defun process-alive-p (process)
306 "Return T if PROCESS is still alive, NIL otherwise."
307 (let ((status (process-status process)))
308 (if (or (eq status :running)
309 (eq status :stopped))
313 (defun process-close (process)
315 "Close all streams connected to PROCESS and stop maintaining the
317 (macrolet ((frob (stream abort)
318 `(when ,stream (close ,stream :abort ,abort))))
320 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process,
321 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
322 (frob (process-output process) nil)
323 (frob (process-error process) nil))
324 ;; FIXME: Given that the status-slot is no longer updated,
325 ;; maybe it should be set to :CLOSED, or similar?
326 (with-active-processes-lock ()
327 (setf *active-processes* (delete process *active-processes*)))
330 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
332 (defun sigchld-handler (ignore1 ignore2 ignore3)
333 (declare (ignore ignore1 ignore2 ignore3))
334 (get-processes-status-changes))
336 (defun get-processes-status-changes ()
339 (multiple-value-bind (pid what code core)
343 (let ((proc (with-active-processes-lock ()
344 (find pid *active-processes* :key #'process-pid))))
346 (setf (process-%status proc) what)
347 (setf (process-exit-code proc) code)
348 (setf (process-core-dumped proc) core)
349 (when (process-status-hook proc)
350 (funcall (process-status-hook proc) proc))
351 (when (position what #(:exited :signaled))
352 (with-active-processes-lock ()
353 (setf *active-processes*
354 (delete proc *active-processes*))))))))
357 (with-active-processes-lock ()
358 (setf *active-processes*
359 (delete-if (lambda (proc)
360 (multiple-value-bind (ok code)
361 (get-exit-code-process (process-pid proc))
362 (when (and (plusp ok) (/= code 259))
363 (setf (process-%status proc) :exited
364 (process-exit-code proc) code)
365 (when (process-status-hook proc)
368 *active-processes*)))
369 ;; Can't call the hooks before all the processes have been deal
370 ;; with, as calling a hook may cause re-entry to
371 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using wait3,
372 ;; but in the Windows implementation is would be deeply bad.
373 (dolist (proc exited)
374 (let ((hook (process-status-hook proc)))
376 (funcall hook proc))))))
378 ;;;; RUN-PROGRAM and close friends
380 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
381 (defvar *close-on-error* nil)
383 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
384 (defvar *close-in-parent* nil)
386 ;;; list of handlers installed by RUN-PROGRAM. FIXME: nothing seems
389 (defvar *handlers-installed* nil)
391 ;;; Find an unused pty. Return three values: the file descriptor for
392 ;;; the master side of the pty, the file descriptor for the slave side
393 ;;; of the pty, and the name of the tty device for the slave side.
396 (define-alien-routine ptsname c-string (fd int))
397 (define-alien-routine grantpt boolean (fd int))
398 (define-alien-routine unlockpt boolean (fd int))
401 ;; First try to use the Unix98 pty api.
402 (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
403 (master-fd (sb-unix:unix-open master-name
409 (let* ((slave-name (ptsname master-fd))
410 (slave-fd (sb-unix:unix-open slave-name
414 (return-from find-a-pty
418 (sb-unix:unix-close master-fd))
419 (error "could not find a pty")))
420 ;; No dice, try using the old-school method.
421 (dolist (char '(#\p #\q))
423 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
425 (master-fd (sb-unix:unix-open master-name
429 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
431 (slave-fd (sb-unix:unix-open slave-name
435 (return-from find-a-pty
439 (sb-unix:unix-close master-fd))))))
440 (error "could not find a pty")))
443 (define-alien-routine openpty int (amaster int :out) (aslave int :out)
444 (name (* char)) (termp (* t)) (winp (* t)))
446 (with-alien ((name-buf (array char 16)))
447 (multiple-value-bind (return-val master-fd slave-fd)
448 (openpty (cast name-buf (* char)) nil nil)
449 (if (zerop return-val)
452 (sb-alien::c-string-to-string (alien-sap name-buf)
453 (sb-impl::default-external-format)
455 (error "could not find a pty"))))))
458 (defun open-pty (pty cookie)
463 (push master *close-on-error*)
464 (push slave *close-in-parent*)
466 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
468 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
469 (push new-fd *close-on-error*)
470 (copy-descriptor-to-stream new-fd pty cookie)))
472 (sb-sys:make-fd-stream master :input t :output t
473 :element-type :default
474 :dual-channel-p t)))))
476 (defmacro round-bytes-to-words (n)
477 (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
478 `(logandc2 (the fixnum (+ (the fixnum ,n)
479 (1- ,bytes-per-word))) (1- ,bytes-per-word))))
481 (defun string-list-to-c-strvec (string-list)
482 (let* ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits))
483 ;; We need an extra for the null, and an extra 'cause exect
484 ;; clobbers argv[-1].
485 (vec-bytes (* bytes-per-word (+ (length string-list) 2)))
486 (octet-vector-list (mapcar (lambda (s)
487 (string-to-octets s :null-terminate t))
489 (string-bytes (reduce #'+ octet-vector-list
491 (round-bytes-to-words (length s)))))
492 (total-bytes (+ string-bytes vec-bytes))
493 ;; Memory to hold the vector of pointers and all the strings.
494 (vec-sap (sb-sys:allocate-system-memory total-bytes))
495 (string-sap (sap+ vec-sap vec-bytes))
496 ;; Index starts from [1]!
497 (vec-index-offset bytes-per-word))
498 (declare (index string-bytes vec-bytes total-bytes)
499 (sb-sys:system-area-pointer vec-sap string-sap))
500 (dolist (octets octet-vector-list)
501 (declare (type (simple-array (unsigned-byte 8) (*)) octets))
502 (let ((size (length octets)))
504 (sb-kernel:copy-ub8-to-system-area octets 0 string-sap 0 size)
505 ;; Put the pointer in the vector.
506 (setf (sap-ref-sap vec-sap vec-index-offset) string-sap)
507 ;; Advance string-sap for the next string.
508 (setf string-sap (sap+ string-sap (round-bytes-to-words size)))
509 (incf vec-index-offset bytes-per-word)))
510 ;; Final null pointer.
511 (setf (sap-ref-sap vec-sap vec-index-offset) (int-sap 0))
512 (values vec-sap (sap+ vec-sap bytes-per-word) total-bytes)))
514 (defmacro with-c-strvec ((var str-list) &body body)
515 (with-unique-names (sap size)
516 `(multiple-value-bind (,sap ,var ,size)
517 (string-list-to-c-strvec ,str-list)
521 (sb-sys:deallocate-system-memory ,sap ,size)))))
523 (sb-alien:define-alien-routine spawn
525 #+win32 sb-win32::handle
526 (program sb-alien:c-string)
527 (argv (* sb-alien:c-string))
529 (stdout sb-alien:int)
530 (stderr sb-alien:int)
531 (search sb-alien:int)
532 (envp (* sb-alien:c-string))
533 (pty-name sb-alien:c-string)
536 ;;; FIXME: There shouldn't be two semiredundant versions of the
537 ;;; documentation. Since this is a public extension function, the
538 ;;; documentation should be in the doc string. So all information from
539 ;;; this comment should be merged into the doc string, and then this
540 ;;; comment can go away.
542 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
543 ;;; Strange stuff happens to keep the Unix state of the world
546 ;;; The child process needs to get its input from somewhere, and send
547 ;;; its output (both standard and error) to somewhere. We have to do
548 ;;; different things depending on where these somewheres really are.
550 ;;; For input, there are five options:
551 ;;; -- T: Just leave fd 0 alone. Pretty simple.
552 ;;; -- "file": Read from the file. We need to open the file and
553 ;;; pull the descriptor out of the stream. The parent should close
554 ;;; this stream after the child is up and running to free any
555 ;;; storage used in the parent.
556 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
557 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
558 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
559 ;;; writeable descriptor, and pass the readable descriptor to
560 ;;; the child. The parent must close the readable descriptor for
561 ;;; EOF to be passed up correctly.
562 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
563 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
564 ;;; everything across.
566 ;;; For output, there are five options:
567 ;;; -- T: Leave descriptor 1 alone.
568 ;;; -- "file": dump output to the file.
569 ;;; -- NIL: dump output to /dev/null.
570 ;;; -- :STREAM: return a stream that can be read from.
571 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
572 ;;; Otherwise, copy stuff from output to stream.
574 ;;; For error, there are all the same options as output plus:
575 ;;; -- :OUTPUT: redirect to the same place as output.
577 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
578 ;;; the fork worked, and NIL if it did not.
579 (defun run-program (program args
581 #-win32 (env nil env-p)
584 (unix-environment-sbcl-from-cmucl env)
591 if-input-does-not-exist
593 (if-output-exists :error)
595 (if-error-exists :error)
600 ;; The Texinfoizer is sensitive to whitespace, so mind the
601 ;; placement of the #-win32 pseudosplicings.
602 "RUN-PROGRAM creates a new process specified by the PROGRAM
603 argument. ARGS are the standard arguments that can be passed to a
604 program. For no arguments, use NIL (which means that just the
605 name of the program is passed as arg 0).
607 The program arguments and the environment are encoded using the
608 default external format for streams.
610 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
611 Users Manual for details about the PROCESS structure."#-win32"
613 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
615 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
616 programs, but unlike the original CMU CL implementation, copies
617 the Unix environment by default.
619 - Running Unix programs from a setuid process, or in any other
620 situation where the Unix environment is under the control of someone
621 else, is a mother lode of security problems. If you are contemplating
622 doing this, read about it first. (The Perl community has a lot of good
623 documentation about this and other security issues in script-like
626 The &KEY arguments have the following meanings:
629 a list of STRINGs describing the new Unix environment
630 (as in \"man environ\"). The default is to copy the environment of
633 an alternative lossy representation of the new Unix environment,
634 for compatibility with CMU CL""
636 Look for PROGRAM in each of the directories in the child's $PATH
637 environment variable. Otherwise an absolute pathname is required.
639 If non-NIL (default), wait until the created process finishes. If
640 NIL, continue running Lisp until the program finishes."#-win32"
642 Either T, NIL, or a stream. Unless NIL, the subprocess is established
643 under a PTY. If :pty is a stream, all output to this pty is sent to
644 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
645 connected to pty that can read output and write input.""
647 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
648 input for the current process is inherited. If NIL, "
649 #-win32"/dev/null"#+win32"nul""
650 is used. If a pathname, the file so specified is used. If a stream,
651 all the input is read from that stream and sent to the subprocess. If
652 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
653 its output to the process. Defaults to NIL.
654 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
656 :ERROR to generate an error
657 :CREATE to create an empty file
658 NIL (the default) to return NIL from RUN-PROGRAM
660 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
661 output for the current process is inherited. If NIL, "
662 #-win32"/dev/null"#+win32"nul""
663 is used. If a pathname, the file so specified is used. If a stream,
664 all the output from the process is written to this stream. If
665 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
666 be read to get the output. Defaults to NIL.
667 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
669 :ERROR (the default) to generate an error
670 :SUPERSEDE to supersede the file with output from the program
671 :APPEND to append output from the program to the file
672 NIL to return NIL from RUN-PROGRAM, without doing anything
673 :ERROR and :IF-ERROR-EXISTS
674 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
675 specified as :OUTPUT in which case all error output is routed to the
676 same place as normal output.
678 This is a function the system calls whenever the status of the
679 process changes. The function takes the process as an argument.")
681 (when (and env-p environment-p)
682 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
683 ;; Make sure that the interrupt handler is installed.
685 (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
686 ;; Prepend the program to the argument list.
687 (push (namestring program) args)
688 (labels (;; It's friendly to allow the caller to pass any string
689 ;; designator, but internally we'd like SIMPLE-STRINGs.
691 ;; Huh? We let users pass in symbols and characters for
692 ;; the arguments, but call NAMESTRING on the program
694 (simplify-args (args)
695 (loop for arg in args
696 as escaped-arg = (escape-arg arg)
697 collect (coerce escaped-arg 'simple-string)))
700 ;; Apparently any spaces or double quotes in the arguments
701 ;; need to be escaped on win32.
702 #+win32 (if (position-if
703 (lambda (c) (find c '(#\" #\Space))) arg)
704 (write-to-string arg)
706 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
707 ;; communicate cleanup info.
710 ;; Some other binding used only on non-Win32. FIXME:
711 ;; nothing seems to set this.
712 #-win32 *handlers-installed*
713 ;; Establish PROC at this level so that we can return it.
715 (simple-args (simplify-args args))
716 (progname (native-namestring program))
720 ;; Note: despite the WITH-* names, these macros don't
721 ;; expand into UNWIND-PROTECT forms. They're just
722 ;; syntactic sugar to make the rest of the routine slightly
724 (macrolet ((with-fd-and-stream-for (((fd stream) which &rest args)
726 `(multiple-value-bind (,fd ,stream)
729 `(get-descriptor-for ,@args))
731 `(if (eq ,(first args) :output)
732 ;; kludge: we expand into
733 ;; hard-coded symbols here.
734 (values stdout output-stream)
735 (get-descriptor-for ,@args))))
737 (with-open-pty (((pty-name pty-stream) (pty cookie)) &body body)
738 #+win32 `(declare (ignore ,pty ,cookie))
739 #+win32 `(let (,pty-name ,pty-stream) ,@body)
740 #-win32 `(multiple-value-bind (,pty-name ,pty-stream)
741 (open-pty ,pty ,cookie)
743 (with-args-vec ((vec args) &body body)
744 `(with-c-strvec (,vec ,args)
746 (with-environment-vec ((vec env) &body body)
747 #+win32 `(let (,vec) ,@body)
748 #-win32 `(with-c-strvec (,vec ,env) ,@body)))
749 (with-fd-and-stream-for ((stdin input-stream) :input
752 :if-does-not-exist if-input-does-not-exist
753 :external-format :default
755 (with-fd-and-stream-for ((stdout output-stream) :output
758 :if-exists if-output-exists
759 :external-format :default)
760 (with-fd-and-stream-for ((stderr error-stream) :error
763 :if-exists if-error-exists
764 :external-format :default)
765 (with-open-pty ((pty-name pty-stream) (pty cookie))
766 ;; Make sure we are not notified about the child
767 ;; death before we have installed the PROCESS
768 ;; structure in *ACTIVE-PROCESSES*.
769 (with-active-processes-lock ()
770 (with-args-vec (args-vec simple-args)
771 (with-environment-vec (environment-vec environment)
774 (spawn progname args-vec
777 environment-vec pty-name
780 (error "couldn't fork child process: ~A"
786 :output output-stream
788 :status-hook status-hook
790 #-win32 (list :pty pty-stream
793 (list :%status :exited
795 (list :%status :running))))
796 (push proc *active-processes*))))))))))
797 (dolist (fd *close-in-parent*)
798 (sb-unix:unix-close fd))
800 (dolist (fd *close-on-error*)
801 (sb-unix:unix-close fd))
802 ;; FIXME: nothing seems to set this.
804 (dolist (handler *handlers-installed*)
805 (sb-sys:remove-fd-handler handler))))
807 (when (and wait proc)
811 ;;; Install a handler for any input that shows up on the file
812 ;;; descriptor. The handler reads the data and writes it to the
814 (defun copy-descriptor-to-stream (descriptor stream cookie external-format)
817 (buf (make-array 256 :element-type '(unsigned-byte 8)))
820 (sb-sys:add-fd-handler
824 (declare (ignore fd))
829 (result readable/errno)
830 (sb-unix:unix-select (1+ descriptor)
834 (if (eql sb-unix:eintr readable/errno)
836 (error "~@<Couldn't select on sub-process: ~
838 (strerror readable/errno))))
841 (multiple-value-bind (count errno)
842 (with-pinned-objects (buf)
843 (sb-unix:unix-read descriptor
844 (sap+ (vector-sap buf) read-end)
845 (- (length buf) read-end)))
847 ((and #-win32 (or (and (null count)
848 (eql errno sb-unix:eio))
850 #+win32 (<= count 0))
851 (sb-sys:remove-fd-handler handler)
854 (sb-unix:unix-close descriptor)
855 (unless (zerop read-end)
856 ;; Should this be an END-OF-FILE?
857 (error "~@<non-empty buffer when EOF reached ~
858 while reading from child: ~S~:>" buf))
861 (sb-sys:remove-fd-handler handler)
865 "~@<couldn't read input from sub-process: ~
869 (incf read-end count)
870 (let* ((decode-end read-end)
871 (string (handler-case
874 :external-format external-format)
875 (end-of-input-in-character (e)
877 (octet-decoding-error-start e))
880 :external-format external-format)))))
881 (unless (zerop (length string))
882 (write-string string stream)
883 (when (/= decode-end (length buf))
884 (replace buf buf :start2 decode-end :end2 read-end))
885 (decf read-end decode-end))))))))))))
887 ;;; FIXME: something very like this is done in SB-POSIX to treat
888 ;;; streams as file descriptor designators; maybe we can combine these
889 ;;; two? Additionally, as we have a couple of user-defined streams
890 ;;; libraries, maybe we should have a generic function for doing this,
891 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
892 ;;; maybe also with SB-POSIX)?
893 (defun get-stream-fd-and-external-format (stream direction)
896 (values (sb-sys:fd-stream-fd stream) nil (stream-external-format stream)))
898 (get-stream-fd-and-external-format
899 (symbol-value (synonym-stream-symbol stream)) direction))
903 (get-stream-fd-and-external-format
904 (two-way-stream-input-stream stream) direction))
906 (get-stream-fd-and-external-format
907 (two-way-stream-output-stream stream) direction))))))
910 ;;; Find a file descriptor to use for object given the direction.
911 ;;; Returns the descriptor. If object is :STREAM, returns the created
912 ;;; stream as the second value.
913 (defun get-descriptor-for (object
916 &key direction (external-format :default) wait
918 (declare (ignore wait)) ;This is explained below.
919 ;; Our use of a temporary file dates back to very old CMUCLs, and
920 ;; was probably only ever intended for use with STRING-STREAMs,
921 ;; which are ordinarily smallish. However, as we've got
922 ;; user-defined stream classes, we can end up trying to copy
923 ;; arbitrarily much data into the temp file, and so are liable to
924 ;; run afoul of disk quotas or to choke on small /tmp file systems.
925 (flet ((make-temp-fd ()
926 (multiple-value-bind (fd name/errno)
927 (sb-unix:sb-mkstemp "/tmp/.run-program-XXXXXX" #o0600)
929 (error "could not open a temporary file: ~A"
930 (strerror name/errno)))
931 (unless (sb-unix:unix-unlink name/errno)
932 (sb-unix:unix-close fd)
933 (error "failed to unlink ~A" name/errno))
936 ;; No new descriptor is needed.
942 (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
943 #+win32 #.(coerce "nul" 'base-string)
945 (:input sb-unix:o_rdonly)
946 (:output sb-unix:o_wronly)
950 (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
951 #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"
953 (push fd *close-in-parent*)
956 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
958 (error "couldn't create pipe: ~A" (strerror write-fd)))
961 (push read-fd *close-in-parent*)
962 (push write-fd *close-on-error*)
963 (let ((stream (sb-sys:make-fd-stream write-fd :output t
964 :element-type :default
967 (values read-fd stream)))
969 (push read-fd *close-on-error*)
970 (push write-fd *close-in-parent*)
971 (let ((stream (sb-sys:make-fd-stream read-fd :input t
972 :element-type :default
975 (values write-fd stream)))
977 (sb-unix:unix-close read-fd)
978 (sb-unix:unix-close write-fd)
979 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
981 ((or (pathnamep object) (stringp object))
982 ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
983 ;; than munge the &rest list for OPEN, just disable keyword
985 (with-open-stream (file (apply #'open object :allow-other-keys t
989 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
991 (push fd *close-in-parent*)
994 (error "couldn't duplicate file descriptor: ~A"
995 (strerror errno)))))))
1000 ;; If we can get an fd for the stream, let the child
1001 ;; process use the fd for its descriptor. Otherwise,
1002 ;; we copy data from the stream into a temp file, and
1003 ;; give the temp file's descriptor to the
1005 (multiple-value-bind (fd stream format)
1006 (get-stream-fd-and-external-format object :input)
1007 (declare (ignore format))
1009 (return (values fd stream))))
1010 ;; FIXME: if we can't get the file descriptor, since
1011 ;; the stream might be interactive or otherwise
1012 ;; block-y, we can't know whether we can copy the
1013 ;; stream's data to a temp file, so if RUN-PROGRAM was
1014 ;; called with :WAIT NIL, we should probably error.
1015 ;; However, STRING-STREAMs aren't fd-streams, but
1016 ;; they're not prone to blocking; any user-defined
1017 ;; streams that "read" from some in-memory data will
1018 ;; probably be similar to STRING-STREAMs. So maybe we
1019 ;; should add a STREAM-INTERACTIVE-P generic function
1020 ;; for problems like this? Anyway, the machinery is
1021 ;; here, if you feel like filling in the details.
1023 (when (and (null wait) #<some undetermined criterion>)
1024 (error "~@<don't know how to get an fd for ~A, and so ~
1025 can't ensure that copying its data to the ~
1026 child process won't hang~:>" object))
1028 (let ((fd (make-temp-fd))
1029 (newline (string #\Newline)))
1031 (multiple-value-bind
1033 (read-line object nil nil)
1036 (let ((vector (string-to-octets line)))
1038 fd vector 0 (length vector)))
1041 (sb-unix:unix-write fd newline 0 1))))
1042 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1043 (push fd *close-in-parent*)
1044 (return (values fd nil)))))
1047 ;; Similar to the :input trick above, except we
1048 ;; arrange to copy data from the stream. This is
1049 ;; slightly saner than the input case, since we don't
1050 ;; buffer to a file, but I think we may still lose if
1051 ;; there's unflushed data in the stream buffer and we
1052 ;; give the file descriptor to the child.
1053 (multiple-value-bind (fd stream format)
1054 (get-stream-fd-and-external-format object :output)
1055 (declare (ignore format))
1057 (return (values fd stream))))
1058 (multiple-value-bind (read-fd write-fd)
1061 (error "couldn't create pipe: ~S" (strerror write-fd)))
1062 (copy-descriptor-to-stream read-fd object cookie
1064 (push read-fd *close-on-error*)
1065 (push write-fd *close-in-parent*)
1066 (return (values write-fd nil)))))))
1068 (error "invalid option to RUN-PROGRAM: ~S" object)))))