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 (type simple-base-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) (type simple-base-string val))
94 (concatenate 'simple-base-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)
158 (sb-thread:with-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))
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
388 (defvar *handlers-installed* nil)
390 ;;; Find an unused pty. Return three values: the file descriptor for
391 ;;; the master side of the pty, the file descriptor for the slave side
392 ;;; of the pty, and the name of the tty device for the slave side.
395 (dolist (char '(#\p #\q))
397 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit) 'base-string))
398 (master-fd (sb-unix:unix-open master-name
402 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit) 'base-string))
403 (slave-fd (sb-unix:unix-open slave-name
407 (return-from find-a-pty
411 (sb-unix:unix-close master-fd))))))
412 (error "could not find a pty"))
415 (defun open-pty (pty cookie)
420 (push master *close-on-error*)
421 (push slave *close-in-parent*)
423 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
425 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
426 (push new-fd *close-on-error*)
427 (copy-descriptor-to-stream new-fd pty cookie)))
429 (sb-sys:make-fd-stream master :input t :output t
430 :element-type :default
431 :dual-channel-p t)))))
433 (defmacro round-bytes-to-words (n)
434 `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
436 (defun string-list-to-c-strvec (string-list)
437 ;; Make a pass over STRING-LIST to calculate the amount of memory
438 ;; needed to hold the strvec.
439 (let ((string-bytes 0)
440 ;; We need an extra for the null, and an extra 'cause exect
441 ;; clobbers argv[-1].
442 (vec-bytes (* #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)
443 (+ (length string-list) 2))))
444 (declare (fixnum string-bytes vec-bytes))
445 (dolist (s string-list)
446 (enforce-type s simple-string)
447 (incf string-bytes (round-bytes-to-words (1+ (length s)))))
448 ;; Now allocate the memory and fill it in.
449 (let* ((total-bytes (+ string-bytes vec-bytes))
450 (vec-sap (sb-sys:allocate-system-memory total-bytes))
451 (string-sap (sap+ vec-sap vec-bytes))
452 (i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)))
453 (declare (type (and unsigned-byte fixnum) total-bytes i)
454 (type sb-sys:system-area-pointer vec-sap string-sap))
455 (dolist (s string-list)
456 (declare (simple-string s))
457 (let ((n (length s)))
458 ;; Blast the string into place.
459 (sb-kernel:copy-ub8-to-system-area (the simple-base-string
461 (coerce s 'simple-base-string))
465 ;; Blast the pointer to the string into place.
466 (setf (sap-ref-sap vec-sap i) string-sap)
467 (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
468 (incf i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits))))
469 ;; Blast in the last null pointer.
470 (setf (sap-ref-sap vec-sap i) (int-sap 0))
471 (values vec-sap (sap+ vec-sap #.(/ sb-vm::n-machine-word-bits
475 (defmacro with-c-strvec ((var str-list) &body body)
476 (with-unique-names (sap size)
477 `(multiple-value-bind
479 (string-list-to-c-strvec ,str-list)
483 (sb-sys:deallocate-system-memory ,sap ,size)))))
486 (sb-alien:define-alien-routine spawn sb-alien:int
487 (program sb-alien:c-string)
488 (argv (* sb-alien:c-string))
489 (envp (* sb-alien:c-string))
490 (pty-name sb-alien:c-string)
492 (stdout sb-alien:int)
493 (stderr sb-alien:int))
496 (sb-alien:define-alien-routine spawn sb-win32::handle
497 (program sb-alien:c-string)
498 (argv (* sb-alien:c-string))
500 (stdout sb-alien:int)
501 (stderr sb-alien:int)
504 ;;; Is UNIX-FILENAME the name of a file that we can execute?
505 (defun unix-filename-is-executable-p (unix-filename)
506 (let ((filename (coerce unix-filename 'base-string)))
507 (values (and (eq (sb-unix:unix-file-kind filename) :file)
509 (sb-unix:unix-access filename sb-unix:x_ok)))))
511 (defun find-executable-in-search-path (pathname &optional
512 (search-path (posix-getenv "PATH")))
514 "Find the first executable file matching PATHNAME in any of the
515 colon-separated list of pathnames SEARCH-PATH"
516 (let ((program #-win32 pathname
517 #+win32 (merge-pathnames pathname (make-pathname :type "exe"))))
518 (loop for end = (position #-win32 #\: #+win32 #\; search-path
519 :start (if end (1+ end) 0))
520 and start = 0 then (and end (1+ end))
522 ;; <Krystof> the truename of a file naming a directory is the
523 ;; directory, at least until pfdietz comes along and says why
524 ;; that's noncompliant -- CSR, c. 2003-08-10
525 for truename = (probe-file (subseq search-path start end))
526 for fullpath = (when truename
527 (unix-namestring (merge-pathnames program truename)))
528 when (and fullpath (unix-filename-is-executable-p fullpath))
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.
576 (defun run-program (program args
579 (environment (if env-p
580 (unix-environment-sbcl-from-cmucl env)
587 if-input-does-not-exist
589 (if-output-exists :error)
591 (if-error-exists :error)
594 "RUN-PROGRAM creates a new Unix process running the Unix program
595 found in the file specified by the PROGRAM argument. ARGS are the
596 standard arguments that can be passed to a Unix program. For no
597 arguments, use NIL (which means that just the name of the program is
600 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
601 Users Manual for details about the PROCESS structure.
603 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
605 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
606 programs, but unlike the original CMU CL implementation, copies
607 the Unix environment by default.
609 - Running Unix programs from a setuid process, or in any other
610 situation where the Unix environment is under the control of someone
611 else, is a mother lode of security problems. If you are contemplating
612 doing this, read about it first. (The Perl community has a lot of good
613 documentation about this and other security issues in script-like
616 The &KEY arguments have the following meanings:
619 a list of SIMPLE-BASE-STRINGs describing the new Unix environment
620 (as in \"man environ\"). The default is to copy the environment of
623 an alternative lossy representation of the new Unix environment,
624 for compatibility with CMU CL
626 Look for PROGRAM in each of the directories along the $PATH
627 environment variable. Otherwise an absolute pathname is required.
628 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
630 If non-NIL (default), wait until the created process finishes. If
631 NIL, continue running Lisp until the program finishes.
633 Either T, NIL, or a stream. Unless NIL, the subprocess is established
634 under a PTY. If :pty is a stream, all output to this pty is sent to
635 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
636 connected to pty that can read output and write input.
638 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
639 input for the current process is inherited. If NIL, /dev/null
640 is used. If a pathname, the file so specified is used. If a stream,
641 all the input is read from that stream and send to the subprocess. If
642 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
643 its output to the process. Defaults to NIL.
644 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
646 :ERROR to generate an error
647 :CREATE to create an empty file
648 NIL (the default) to return NIL from RUN-PROGRAM
650 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
651 output for the current process is inherited. If NIL, /dev/null
652 is used. If a pathname, the file so specified is used. If a stream,
653 all the output from the process is written to this stream. If
654 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
655 be read to get the output. Defaults to NIL.
656 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
658 :ERROR (the default) to generate an error
659 :SUPERSEDE to supersede the file with output from the program
660 :APPEND to append output from the program to the file
661 NIL to return NIL from RUN-PROGRAM, without doing anything
662 :ERROR and :IF-ERROR-EXISTS
663 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
664 specified as :OUTPUT in which case all error output is routed to the
665 same place as normal output.
667 This is a function the system calls whenever the status of the
668 process changes. The function takes the process as an argument."
669 (when (and env-p environment-p)
670 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
671 ;; Make sure that the interrupt handler is installed.
672 (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
673 ;; Prepend the program to the argument list.
674 (push (namestring program) args)
675 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
676 ;; communicate cleanup info.
680 ;; Establish PROC at this level so that we can return it.
682 ;; It's friendly to allow the caller to pass any string
683 ;; designator, but internally we'd like SIMPLE-STRINGs.
684 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
688 (find-executable-in-search-path program)
689 (unix-namestring program)))
692 (error "no such program: ~S" program))
693 (unless (unix-filename-is-executable-p pfile)
694 (error "not executable: ~S" program))
695 (multiple-value-bind (stdin input-stream)
696 (get-descriptor-for input cookie
698 :if-does-not-exist if-input-does-not-exist)
699 (multiple-value-bind (stdout output-stream)
700 (get-descriptor-for output cookie
702 :if-exists if-output-exists)
703 (multiple-value-bind (stderr error-stream)
704 (if (eq error :output)
705 (values stdout output-stream)
706 (get-descriptor-for error cookie
708 :if-exists if-error-exists))
709 (multiple-value-bind (pty-name pty-stream)
710 (open-pty pty cookie)
711 ;; Make sure we are not notified about the child
712 ;; death before we have installed the PROCESS
713 ;; structure in *ACTIVE-PROCESSES*.
714 (with-active-processes-lock ()
715 (with-c-strvec (args-vec simple-args)
716 (with-c-strvec (environment-vec environment)
719 (spawn pfile args-vec environment-vec pty-name
720 stdin stdout stderr))))
721 (when (< child-pid 0)
722 (error "couldn't fork child process: ~A"
724 (setf proc (make-process :pid child-pid
728 :output output-stream
730 :status-hook status-hook
732 (push proc *active-processes*))))))))))
733 (dolist (fd *close-in-parent*)
734 (sb-unix:unix-close fd))
736 (dolist (fd *close-on-error*)
737 (sb-unix:unix-close fd))
738 (dolist (handler *handlers-installed*)
739 (sb-sys:remove-fd-handler handler))))
740 (when (and wait proc)
745 (defun run-program (program args
750 if-input-does-not-exist
752 (if-output-exists :error)
754 (if-error-exists :error)
756 "RUN-PROGRAM creates a new process specified by the PROGRAM
757 argument. ARGS are the standard arguments that can be passed to a
758 program. For no arguments, use NIL (which means that just the name of
759 the program is passed as arg 0).
761 RUN-PROGRAM will either return a PROCESS structure. See the CMU
762 Common Lisp Users Manual for details about the PROCESS structure.
764 The &KEY arguments have the following meanings:
766 Look for PROGRAM in each of the directories along the $PATH
767 environment variable. Otherwise an absolute pathname is required.
768 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
770 If non-NIL (default), wait until the created process finishes. If
771 NIL, continue running Lisp until the program finishes.
773 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
774 input for the current process is inherited. If NIL, /dev/null
775 is used. If a pathname, the file so specified is used. If a stream,
776 all the input is read from that stream and send to the subprocess. If
777 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
778 its output to the process. Defaults to NIL.
779 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
781 :ERROR to generate an error
782 :CREATE to create an empty file
783 NIL (the default) to return NIL from RUN-PROGRAM
785 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
786 output for the current process is inherited. If NIL, /dev/null
787 is used. If a pathname, the file so specified is used. If a stream,
788 all the output from the process is written to this stream. If
789 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
790 be read to get the output. Defaults to NIL.
791 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
793 :ERROR (the default) to generate an error
794 :SUPERSEDE to supersede the file with output from the program
795 :APPEND to append output from the program to the file
796 NIL to return NIL from RUN-PROGRAM, without doing anything
797 :ERROR and :IF-ERROR-EXISTS
798 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
799 specified as :OUTPUT in which case all error output is routed to the
800 same place as normal output.
802 This is a function the system calls whenever the status of the
803 process changes. The function takes the process as an argument."
804 ;; Prepend the program to the argument list.
805 (push (namestring program) args)
806 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
807 ;; communicate cleanup info.
810 ;; Establish PROC at this level so that we can return it.
812 ;; It's friendly to allow the caller to pass any string
813 ;; designator, but internally we'd like SIMPLE-STRINGs.
814 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
818 (find-executable-in-search-path program)
819 (unix-namestring program)))
822 (error "No such program: ~S" program))
823 (unless (unix-filename-is-executable-p pfile)
824 (error "Not an executable: ~S" program))
825 (multiple-value-bind (stdin input-stream)
826 (get-descriptor-for input cookie
828 :if-does-not-exist if-input-does-not-exist)
829 (multiple-value-bind (stdout output-stream)
830 (get-descriptor-for output cookie
832 :if-exists if-output-exists)
833 (multiple-value-bind (stderr error-stream)
834 (if (eq error :output)
835 (values stdout output-stream)
836 (get-descriptor-for error cookie
838 :if-exists if-error-exists))
839 (with-c-strvec (args-vec simple-args)
840 (let ((handle (without-gcing
841 (spawn pfile args-vec
845 (error "Couldn't spawn program: ~A" (strerror)))
848 (make-process :%status :exited
850 (make-process :pid handle
853 :output output-stream
855 :status-hook status-hook
856 :cookie cookie))))))))))
857 ;; FIXME: this should probably use PROCESS-WAIT instead instead
858 ;; of special argument to SPAWN.
860 (push proc *active-processes*))
861 (when (and wait status-hook)
862 (funcall status-hook proc))
865 ;;; Install a handler for any input that shows up on the file
866 ;;; descriptor. The handler reads the data and writes it to the
868 (defun copy-descriptor-to-stream (descriptor stream cookie)
870 (let ((string (make-string 256 :element-type 'base-char))
873 (sb-sys:add-fd-handler
876 (declare (ignore fd))
881 (result readable/errno)
882 (sb-unix:unix-select (1+ descriptor)
886 (error "~@<couldn't select on sub-process: ~
888 (strerror readable/errno)))
891 (sb-alien:with-alien ((buf (sb-alien:array
896 (sb-unix:unix-read descriptor
899 (cond (#-win32(or (and (null count)
900 (eql errno sb-unix:eio))
903 (sb-sys:remove-fd-handler handler)
906 (sb-unix:unix-close descriptor)
909 (sb-sys:remove-fd-handler handler)
913 "~@<couldn't read input from sub-process: ~
917 (sb-kernel:copy-ub8-from-system-area
921 (write-string string stream
922 :end count)))))))))))
924 ;;; Find a file descriptor to use for object given the direction.
925 ;;; Returns the descriptor. If object is :STREAM, returns the created
926 ;;; stream as the second value.
927 (defun get-descriptor-for (object
933 ;; No new descriptor is needed.
939 (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
940 #+win32 #.(coerce "nul" 'base-string)
942 (:input sb-unix:o_rdonly)
943 (:output sb-unix:o_wronly)
947 (error "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
949 (push fd *close-in-parent*)
952 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
954 (error "couldn't create pipe: ~A" (strerror write-fd)))
957 (push read-fd *close-in-parent*)
958 (push write-fd *close-on-error*)
959 (let ((stream (sb-sys:make-fd-stream write-fd :output t
960 :element-type :default)))
961 (values read-fd stream)))
963 (push read-fd *close-on-error*)
964 (push write-fd *close-in-parent*)
965 (let ((stream (sb-sys:make-fd-stream read-fd :input t
966 :element-type :default)))
967 (values write-fd stream)))
969 (sb-unix:unix-close read-fd)
970 (sb-unix:unix-close write-fd)
971 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
973 ((or (pathnamep object) (stringp object))
974 (with-open-stream (file (apply #'open object keys))
977 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
979 (push fd *close-in-parent*)
982 (error "couldn't duplicate file descriptor: ~A"
983 (strerror errno)))))))
984 ((sb-sys:fd-stream-p object)
985 (values (sb-sys:fd-stream-fd object) nil))
989 ;; FIXME: We could use a better way of setting up
990 ;; temporary files, both here and in LOAD-FOREIGN.
993 (error "could not open a temporary file in /tmp"))
994 (let* ((name (coerce (format nil "/tmp/.run-program-~D" count)
996 (fd (sb-unix:unix-open name
997 (logior sb-unix:o_rdwr
1001 (sb-unix:unix-unlink name)
1003 (let ((newline (string #\Newline)))
1005 (multiple-value-bind
1007 (read-line object nil nil)
1012 ;; FIXME: this really should be
1013 ;; (STRING-TO-OCTETS :EXTERNAL-FORMAT ...).
1014 ;; RUN-PROGRAM should take an
1015 ;; external-format argument, which should
1016 ;; be passed down to here. Something
1017 ;; similar should happen on :OUTPUT, too.
1018 (map '(vector (unsigned-byte 8)) #'char-code line)
1022 (sb-unix:unix-write fd newline 0 1)))))
1023 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1024 (push fd *close-in-parent*)
1025 (return (values fd nil))))))
1027 (multiple-value-bind (read-fd write-fd)
1030 (error "couldn't create pipe: ~S" (strerror write-fd)))
1031 (copy-descriptor-to-stream read-fd object cookie)
1032 (push read-fd *close-on-error*)
1033 (push write-fd *close-in-parent*)
1034 (values write-fd nil)))))
1036 (error "invalid option to RUN-PROGRAM: ~S" object))))