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 ("waitpid" c-waitpid) sb-alien:int
102 (status sb-alien:int :out)
103 (options sb-alien:int))
106 (defun waitpid (pid &optional do-not-hang check-for-stopped)
108 "Return any available status information on child process with PID."
109 (multiple-value-bind (pid status)
111 (logior (if do-not-hang
114 (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*)
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))
277 (find-current-foreground-process process)))))
282 (sb-unix:unix-killpg pid signal))
284 (sb-unix:unix-kill pid signal)))
287 ((and (eql pid (process-pid process))
288 (= signal sb-unix:sigcont))
289 (setf (process-%status process) :running)
290 (setf (process-exit-code process) nil)
291 (when (process-status-hook process)
292 (funcall (process-status-hook process) process))
297 (defun process-alive-p (process)
299 "Return T if PROCESS is still alive, NIL otherwise."
300 (let ((status (process-status process)))
301 (if (or (eq status :running)
302 (eq status :stopped))
306 (defun process-close (process)
308 "Close all streams connected to PROCESS and stop maintaining the
310 (macrolet ((frob (stream abort)
311 `(when ,stream (close ,stream :abort ,abort))))
313 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process,
314 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
315 (frob (process-output process) nil)
316 (frob (process-error process) nil))
317 ;; FIXME: Given that the status-slot is no longer updated,
318 ;; maybe it should be set to :CLOSED, or similar?
319 (with-active-processes-lock ()
320 (setf *active-processes* (delete process *active-processes*)))
323 (defun get-processes-status-changes ()
325 (with-active-processes-lock ()
326 (setf *active-processes*
329 ;; Wait only on pids belonging to processes
330 ;; started by RUN-PROGRAM. There used to be a
331 ;; WAIT3 call here, but that makes direct
332 ;; WAIT, WAITPID usage impossible due to the
333 ;; race with the SIGCHLD signal handler.
334 (multiple-value-bind (pid what code core)
335 (waitpid (process-pid proc) t t)
337 (setf (process-%status proc) what)
338 (setf (process-exit-code proc) code)
339 (setf (process-core-dumped proc) core)
340 (when (process-status-hook proc)
345 (multiple-value-bind (ok code)
346 (get-exit-code-process (process-pid proc))
347 (when (and (plusp ok) (/= code 259))
348 (setf (process-%status proc) :exited
349 (process-exit-code proc) code)
350 (when (process-status-hook proc)
353 *active-processes*)))
354 ;; Can't call the hooks before all the processes have been deal
355 ;; with, as calling a hook may cause re-entry to
356 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using waitpid,
357 ;; but in the Windows implementation it would be deeply bad.
358 (dolist (proc exited)
359 (let ((hook (process-status-hook proc)))
361 (funcall hook proc))))))
363 ;;;; RUN-PROGRAM and close friends
365 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
366 (defvar *close-on-error* nil)
368 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
369 (defvar *close-in-parent* nil)
371 ;;; list of handlers installed by RUN-PROGRAM. FIXME: nothing seems
374 (defvar *handlers-installed* nil)
376 ;;; Find an unused pty. Return three values: the file descriptor for
377 ;;; the master side of the pty, the file descriptor for the slave side
378 ;;; of the pty, and the name of the tty device for the slave side.
381 (define-alien-routine ptsname c-string (fd int))
382 (define-alien-routine grantpt boolean (fd int))
383 (define-alien-routine unlockpt boolean (fd int))
386 ;; First try to use the Unix98 pty api.
387 (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
388 (master-fd (sb-unix:unix-open master-name
394 (let* ((slave-name (ptsname master-fd))
395 (slave-fd (sb-unix:unix-open slave-name
399 (return-from find-a-pty
403 (sb-unix:unix-close master-fd))
404 (error "could not find a pty")))
405 ;; No dice, try using the old-school method.
406 (dolist (char '(#\p #\q))
408 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
410 (master-fd (sb-unix:unix-open master-name
414 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
416 (slave-fd (sb-unix:unix-open slave-name
420 (return-from find-a-pty
424 (sb-unix:unix-close master-fd))))))
425 (error "could not find a pty")))
428 (define-alien-routine openpty int (amaster int :out) (aslave int :out)
429 (name (* char)) (termp (* t)) (winp (* t)))
431 (with-alien ((name-buf (array char 16)))
432 (multiple-value-bind (return-val master-fd slave-fd)
433 (openpty (cast name-buf (* char)) nil nil)
434 (if (zerop return-val)
437 (sb-alien::c-string-to-string (alien-sap name-buf)
438 (sb-impl::default-external-format)
440 (error "could not find a pty"))))))
443 (defun open-pty (pty cookie &key (external-format :default))
448 (push master *close-on-error*)
449 (push slave *close-in-parent*)
451 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
453 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
454 (push new-fd *close-on-error*)
455 (copy-descriptor-to-stream new-fd pty cookie external-format)))
457 (sb-sys:make-fd-stream master :input t :output t
458 :element-type :default
459 :dual-channel-p t)))))
461 ;; Null terminate strings only C-side: otherwise we can run into
462 ;; A-T-S-L even for simple encodings like ASCII. Multibyte encodings
463 ;; may need more than a single byte of zeros; assume 4 byte is enough
465 (defmacro round-null-terminated-bytes-to-words (n)
466 (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
467 `(logandc2 (the sb-vm:signed-word (+ (the fixnum ,n)
468 4 (1- ,bytes-per-word)))
469 (1- ,bytes-per-word))))
471 (defun string-list-to-c-strvec (string-list)
472 (let* ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits))
473 ;; We need an extra for the null, and an extra 'cause exect
474 ;; clobbers argv[-1].
475 (vec-bytes (* bytes-per-word (+ (length string-list) 2)))
476 (octet-vector-list (mapcar (lambda (s)
477 (string-to-octets s))
479 (string-bytes (reduce #'+ octet-vector-list
481 (round-null-terminated-bytes-to-words
483 (total-bytes (+ string-bytes vec-bytes))
484 ;; Memory to hold the vector of pointers and all the strings.
485 (vec-sap (sb-sys:allocate-system-memory total-bytes))
486 (string-sap (sap+ vec-sap vec-bytes))
487 ;; Index starts from [1]!
488 (vec-index-offset bytes-per-word))
489 (declare (sb-vm:signed-word vec-bytes)
490 (sb-vm:word string-bytes total-bytes)
491 (sb-sys:system-area-pointer vec-sap string-sap))
492 (dolist (octets octet-vector-list)
493 (declare (type (simple-array (unsigned-byte 8) (*)) octets))
494 (let ((size (length octets)))
496 (sb-kernel:copy-ub8-to-system-area octets 0 string-sap 0 size)
498 (setf (sap-ref-32 string-sap size) 0)
499 ;; Put the pointer in the vector.
500 (setf (sap-ref-sap vec-sap vec-index-offset) string-sap)
501 ;; Advance string-sap for the next string.
502 (setf string-sap (sap+ string-sap
503 (round-null-terminated-bytes-to-words size)))
504 (incf vec-index-offset bytes-per-word)))
505 ;; Final null pointer.
506 (setf (sap-ref-sap vec-sap vec-index-offset) (int-sap 0))
507 (values vec-sap (sap+ vec-sap bytes-per-word) total-bytes)))
509 (defmacro with-c-strvec ((var str-list) &body body)
510 (with-unique-names (sap size)
511 `(multiple-value-bind (,sap ,var ,size)
512 (string-list-to-c-strvec ,str-list)
516 (sb-sys:deallocate-system-memory ,sap ,size)))))
518 (sb-alien:define-alien-routine spawn
520 #+win32 sb-win32::handle
521 (program sb-alien:c-string)
522 (argv (* sb-alien:c-string))
524 (stdout sb-alien:int)
525 (stderr sb-alien:int)
526 (search sb-alien:int)
527 (envp (* sb-alien:c-string))
528 (pty-name sb-alien:c-string)
531 ;;; FIXME: There shouldn't be two semiredundant versions of the
532 ;;; documentation. Since this is a public extension function, the
533 ;;; documentation should be in the doc string. So all information from
534 ;;; this comment should be merged into the doc string, and then this
535 ;;; comment can go away.
537 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
538 ;;; Strange stuff happens to keep the Unix state of the world
541 ;;; The child process needs to get its input from somewhere, and send
542 ;;; its output (both standard and error) to somewhere. We have to do
543 ;;; different things depending on where these somewheres really are.
545 ;;; For input, there are five options:
546 ;;; -- T: Just leave fd 0 alone. Pretty simple.
547 ;;; -- "file": Read from the file. We need to open the file and
548 ;;; pull the descriptor out of the stream. The parent should close
549 ;;; this stream after the child is up and running to free any
550 ;;; storage used in the parent.
551 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
552 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
553 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
554 ;;; writeable descriptor, and pass the readable descriptor to
555 ;;; the child. The parent must close the readable descriptor for
556 ;;; EOF to be passed up correctly.
557 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
558 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
559 ;;; everything across.
561 ;;; For output, there are five options:
562 ;;; -- T: Leave descriptor 1 alone.
563 ;;; -- "file": dump output to the file.
564 ;;; -- NIL: dump output to /dev/null.
565 ;;; -- :STREAM: return a stream that can be read from.
566 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
567 ;;; Otherwise, copy stuff from output to stream.
569 ;;; For error, there are all the same options as output plus:
570 ;;; -- :OUTPUT: redirect to the same place as output.
572 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
573 ;;; the fork worked, and NIL if it did not.
574 (defun run-program (program args
576 #-win32 (env nil env-p)
579 (unix-environment-sbcl-from-cmucl env)
586 if-input-does-not-exist
588 (if-output-exists :error)
590 (if-error-exists :error)
592 (external-format :default))
596 ;; The Texinfoizer is sensitive to whitespace, so mind the
597 ;; placement of the #-win32 pseudosplicings.
598 "RUN-PROGRAM creates a new process specified by the PROGRAM
599 argument. ARGS are the standard arguments that can be passed to a
600 program. For no arguments, use NIL (which means that just the
601 name of the program is passed as arg 0).
603 The program arguments and the environment are encoded using the
604 default external format for streams.
606 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
607 Users Manual for details about the PROCESS structure."#-win32"
609 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
611 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
612 programs, but unlike the original CMU CL implementation, copies
613 the Unix environment by default.
615 - Running Unix programs from a setuid process, or in any other
616 situation where the Unix environment is under the control of someone
617 else, is a mother lode of security problems. If you are contemplating
618 doing this, read about it first. (The Perl community has a lot of good
619 documentation about this and other security issues in script-like
622 The &KEY arguments have the following meanings:
625 a list of STRINGs describing the new Unix environment
626 (as in \"man environ\"). The default is to copy the environment of
629 an alternative lossy representation of the new Unix environment,
630 for compatibility with CMU CL""
632 Look for PROGRAM in each of the directories in the child's $PATH
633 environment variable. Otherwise an absolute pathname is required.
635 If non-NIL (default), wait until the created process finishes. If
636 NIL, continue running Lisp until the program finishes."#-win32"
638 Either T, NIL, or a stream. Unless NIL, the subprocess is established
639 under a PTY. If :pty is a stream, all output to this pty is sent to
640 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
641 connected to pty that can read output and write input.""
643 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
644 input for the current process is inherited. If NIL, "
645 #-win32"/dev/null"#+win32"nul""
646 is used. If a pathname, the file so specified is used. If a stream,
647 all the input is read from that stream and sent to the subprocess. If
648 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
649 its output to the process. Defaults to NIL.
650 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
652 :ERROR to generate an error
653 :CREATE to create an empty file
654 NIL (the default) to return NIL from RUN-PROGRAM
656 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
657 output for the current process is inherited. If NIL, "
658 #-win32"/dev/null"#+win32"nul""
659 is used. If a pathname, the file so specified is used. If a stream,
660 all the output from the process is written to this stream. If
661 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
662 be read to get the output. Defaults to NIL.
663 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
665 :ERROR (the default) to generate an error
666 :SUPERSEDE to supersede the file with output from the program
667 :APPEND to append output from the program to the file
668 NIL to return NIL from RUN-PROGRAM, without doing anything
669 :ERROR and :IF-ERROR-EXISTS
670 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
671 specified as :OUTPUT in which case all error output is routed to the
672 same place as normal output.
674 This is a function the system calls whenever the status of the
675 process changes. The function takes the process as an argument.
677 The external-format to use for :INPUT, :OUTPUT, and :ERROR :STREAMs.")
679 (when (and env-p environment-p)
680 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
681 ;; Prepend the program to the argument list.
682 (push (namestring program) args)
683 (labels (;; It's friendly to allow the caller to pass any string
684 ;; designator, but internally we'd like SIMPLE-STRINGs.
686 ;; Huh? We let users pass in symbols and characters for
687 ;; the arguments, but call NAMESTRING on the program
689 (simplify-args (args)
690 (loop for arg in args
691 as escaped-arg = (escape-arg arg)
692 collect (coerce escaped-arg 'simple-string)))
695 ;; Apparently any spaces or double quotes in the arguments
696 ;; need to be escaped on win32.
697 #+win32 (if (position-if
698 (lambda (c) (find c '(#\" #\Space))) arg)
699 (write-to-string arg)
701 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
702 ;; communicate cleanup info.
705 ;; Some other binding used only on non-Win32. FIXME:
706 ;; nothing seems to set this.
707 #-win32 *handlers-installed*
708 ;; Establish PROC at this level so that we can return it.
710 (simple-args (simplify-args args))
711 (progname (native-namestring program))
715 ;; Note: despite the WITH-* names, these macros don't
716 ;; expand into UNWIND-PROTECT forms. They're just
717 ;; syntactic sugar to make the rest of the routine slightly
719 (macrolet ((with-fd-and-stream-for (((fd stream) which &rest args)
721 `(multiple-value-bind (,fd ,stream)
724 `(get-descriptor-for ,@args))
726 `(if (eq ,(first args) :output)
727 ;; kludge: we expand into
728 ;; hard-coded symbols here.
729 (values stdout output-stream)
730 (get-descriptor-for ,@args))))
732 (with-open-pty (((pty-name pty-stream) (pty cookie))
734 #+win32 `(declare (ignore ,pty ,cookie))
735 #+win32 `(let (,pty-name ,pty-stream) ,@body)
736 #-win32 `(multiple-value-bind (,pty-name ,pty-stream)
737 (open-pty ,pty ,cookie)
739 (with-args-vec ((vec args) &body body)
740 `(with-c-strvec (,vec ,args)
742 (with-environment-vec ((vec env) &body body)
743 #+win32 `(let (,vec) ,@body)
744 #-win32 `(with-c-strvec (,vec ,env) ,@body)))
745 (with-fd-and-stream-for ((stdin input-stream) :input
748 :if-does-not-exist if-input-does-not-exist
749 :external-format external-format
751 (with-fd-and-stream-for ((stdout output-stream) :output
754 :if-exists if-output-exists
755 :external-format external-format)
756 (with-fd-and-stream-for ((stderr error-stream) :error
759 :if-exists if-error-exists
760 :external-format external-format)
761 (with-open-pty ((pty-name pty-stream) (pty cookie))
762 ;; Make sure we are not notified about the child
763 ;; death before we have installed the PROCESS
764 ;; structure in *ACTIVE-PROCESSES*.
766 (with-active-processes-lock ()
767 (with-args-vec (args-vec simple-args)
768 (with-environment-vec (environment-vec environment)
769 (setq child (without-gcing
770 (spawn progname args-vec
773 environment-vec pty-name
781 :output output-stream
783 :status-hook status-hook
785 #-win32 (list :pty pty-stream
788 (list :%status :exited
790 (list :%status :running))))
791 (push proc *active-processes*)))))
792 ;; Report the error outside the lock.
794 (error "couldn't fork child process: ~A"
796 (dolist (fd *close-in-parent*)
797 (sb-unix:unix-close fd))
799 (dolist (fd *close-on-error*)
800 (sb-unix:unix-close fd))
801 ;; FIXME: nothing seems to set this.
803 (dolist (handler *handlers-installed*)
804 (sb-sys:remove-fd-handler handler))))
806 (when (and wait proc)
810 ;;; Install a handler for any input that shows up on the file
811 ;;; descriptor. The handler reads the data and writes it to the
813 (defun copy-descriptor-to-stream (descriptor stream cookie external-format)
816 (buf (make-array 256 :element-type '(unsigned-byte 8)))
818 (et (stream-element-type stream))
821 ((member et '(character base-char))
823 (let* ((decode-end read-end)
824 (string (handler-case
827 :external-format external-format)
828 (end-of-input-in-character (e)
830 (octet-decoding-error-start e))
833 :external-format external-format)))))
834 (unless (zerop (length string))
835 (write-string string stream)
836 (when (/= decode-end (length buf))
837 (replace buf buf :start2 decode-end :end2 read-end))
838 (decf read-end decode-end)))))
839 ((member et '(:default (unsigned-byte 8)) :test #'equal)
841 (write-sequence buf stream :end read-end)
845 (error "Don't know how to copy to stream of element-type ~S"
848 (sb-sys:add-fd-handler
852 (declare (ignore fd))
857 (result readable/errno)
858 (sb-unix:unix-select (1+ descriptor)
862 (if (eql sb-unix:eintr readable/errno)
864 (error "~@<Couldn't select on sub-process: ~
866 (strerror readable/errno))))
869 (multiple-value-bind (count errno)
870 (with-pinned-objects (buf)
871 (sb-unix:unix-read descriptor
872 (sap+ (vector-sap buf) read-end)
873 (- (length buf) read-end)))
875 ((and #-win32 (or (and (null count)
876 (eql errno sb-unix:eio))
878 #+win32 (<= count 0))
879 (sb-sys:remove-fd-handler handler)
882 (sb-unix:unix-close descriptor)
883 (unless (zerop read-end)
884 ;; Should this be an END-OF-FILE?
885 (error "~@<non-empty buffer when EOF reached ~
886 while reading from child: ~S~:>" buf))
889 (sb-sys:remove-fd-handler handler)
893 "~@<couldn't read input from sub-process: ~
897 (incf read-end count)
898 (funcall copy-fun))))))))))
900 ;;; FIXME: something very like this is done in SB-POSIX to treat
901 ;;; streams as file descriptor designators; maybe we can combine these
902 ;;; two? Additionally, as we have a couple of user-defined streams
903 ;;; libraries, maybe we should have a generic function for doing this,
904 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
905 ;;; maybe also with SB-POSIX)?
906 (defun get-stream-fd-and-external-format (stream direction)
909 (values (sb-sys:fd-stream-fd stream) nil (stream-external-format stream)))
911 (get-stream-fd-and-external-format
912 (symbol-value (synonym-stream-symbol stream)) direction))
916 (get-stream-fd-and-external-format
917 (two-way-stream-input-stream stream) direction))
919 (get-stream-fd-and-external-format
920 (two-way-stream-output-stream stream) direction))))))
923 ;;; Find a file descriptor to use for object given the direction.
924 ;;; Returns the descriptor. If object is :STREAM, returns the created
925 ;;; stream as the second value.
926 (defun get-descriptor-for (object
929 &key direction (external-format :default) wait
931 (declare (ignore wait)) ;This is explained below.
932 ;; Our use of a temporary file dates back to very old CMUCLs, and
933 ;; was probably only ever intended for use with STRING-STREAMs,
934 ;; which are ordinarily smallish. However, as we've got
935 ;; user-defined stream classes, we can end up trying to copy
936 ;; arbitrarily much data into the temp file, and so are liable to
937 ;; run afoul of disk quotas or to choke on small /tmp file systems.
938 (flet ((make-temp-fd ()
939 (multiple-value-bind (fd name/errno)
940 (sb-unix:sb-mkstemp "/tmp/.run-program-XXXXXX" #o0600)
942 (error "could not open a temporary file: ~A"
943 (strerror name/errno)))
944 (unless (sb-unix:unix-unlink name/errno)
945 (sb-unix:unix-close fd)
946 (error "failed to unlink ~A" name/errno))
949 ;; No new descriptor is needed.
952 (and (typep object 'broadcast-stream)
953 (not (broadcast-stream-streams object))))
957 (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
958 #+win32 #.(coerce "nul" 'base-string)
960 (:input sb-unix:o_rdonly)
961 (:output sb-unix:o_wronly)
965 (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
966 #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"
968 (push fd *close-in-parent*)
971 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
973 (error "couldn't create pipe: ~A" (strerror write-fd)))
976 (push read-fd *close-in-parent*)
977 (push write-fd *close-on-error*)
978 (let ((stream (sb-sys:make-fd-stream write-fd :output t
979 :element-type :default
982 (values read-fd stream)))
984 (push read-fd *close-on-error*)
985 (push write-fd *close-in-parent*)
986 (let ((stream (sb-sys:make-fd-stream read-fd :input t
987 :element-type :default
990 (values write-fd stream)))
992 (sb-unix:unix-close read-fd)
993 (sb-unix:unix-close write-fd)
994 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
996 ((or (pathnamep object) (stringp object))
997 ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
998 ;; than munge the &rest list for OPEN, just disable keyword
1000 (with-open-stream (file (apply #'open object :allow-other-keys t
1002 (multiple-value-bind
1004 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
1006 (push fd *close-in-parent*)
1009 (error "couldn't duplicate file descriptor: ~A"
1010 (strerror errno)))))))
1015 ;; If we can get an fd for the stream, let the child
1016 ;; process use the fd for its descriptor. Otherwise,
1017 ;; we copy data from the stream into a temp file, and
1018 ;; give the temp file's descriptor to the
1020 (multiple-value-bind (fd stream format)
1021 (get-stream-fd-and-external-format object :input)
1022 (declare (ignore format))
1024 (return (values fd stream))))
1025 ;; FIXME: if we can't get the file descriptor, since
1026 ;; the stream might be interactive or otherwise
1027 ;; block-y, we can't know whether we can copy the
1028 ;; stream's data to a temp file, so if RUN-PROGRAM was
1029 ;; called with :WAIT NIL, we should probably error.
1030 ;; However, STRING-STREAMs aren't fd-streams, but
1031 ;; they're not prone to blocking; any user-defined
1032 ;; streams that "read" from some in-memory data will
1033 ;; probably be similar to STRING-STREAMs. So maybe we
1034 ;; should add a STREAM-INTERACTIVE-P generic function
1035 ;; for problems like this? Anyway, the machinery is
1036 ;; here, if you feel like filling in the details.
1038 (when (and (null wait) #<some undetermined criterion>)
1039 (error "~@<don't know how to get an fd for ~A, and so ~
1040 can't ensure that copying its data to the ~
1041 child process won't hang~:>" object))
1043 (let ((fd (make-temp-fd))
1044 (et (stream-element-type object)))
1045 (cond ((member et '(character base-char))
1047 (multiple-value-bind
1049 (read-line object nil nil)
1052 (let ((vector (string-to-octets
1054 :external-format external-format)))
1056 fd vector 0 (length vector)))
1060 fd #.(string #\Newline) 0 1)))))
1061 ((member et '(:default (unsigned-byte 8))
1063 (loop with buf = (make-array 256 :element-type '(unsigned-byte 8))
1064 for p = (read-sequence buf object)
1066 do (sb-unix:unix-write fd buf 0 p)))
1068 (error "Don't know how to copy from stream of element-type ~S"
1070 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1071 (push fd *close-in-parent*)
1072 (return (values fd nil)))))
1075 ;; Similar to the :input trick above, except we
1076 ;; arrange to copy data from the stream. This is
1077 ;; slightly saner than the input case, since we don't
1078 ;; buffer to a file, but I think we may still lose if
1079 ;; there's unflushed data in the stream buffer and we
1080 ;; give the file descriptor to the child.
1081 (multiple-value-bind (fd stream format)
1082 (get-stream-fd-and-external-format object :output)
1083 (declare (ignore format))
1085 (return (values fd stream))))
1086 (multiple-value-bind (read-fd write-fd)
1089 (error "couldn't create pipe: ~S" (strerror write-fd)))
1090 (copy-descriptor-to-stream read-fd object cookie
1092 (push read-fd *close-on-error*)
1093 (push write-fd *close-in-parent*)
1094 (return (values write-fd nil)))))))
1096 (error "invalid option to RUN-PROGRAM: ~S" object)))))