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 ()
53 "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
54 (c-strings->string-list
(wrapped-environ))))
58 (defun decode-windows-environment (environment)
59 (loop until
(zerop (sap-ref-8 environment
0))
61 (let ((string (sb-alien::c-string-to-string environment
62 (sb-alien::default-c-string-external-format
)
64 (loop for value
= (sap-ref-8 environment
0)
65 do
(setf environment
(sap+ environment
1))
69 (defun encode-windows-environment (list)
70 (let* ((external-format (sb-alien::default-c-string-external-format
))
72 (length 1)) ;; 1 for \0 at the very end
76 (string-to-octets x
:external-format external-format
80 (incf length
(length octet
))))
81 (let ((mem (allocate-system-memory length
))
84 (loop for string in octets
85 for length
= (length string
)
87 (copy-ub8-to-system-area string
0 mem index length
)
89 (setf (sap-ref-8 mem index
) 0)
90 (values mem mem length
))))
92 (defun posix-environ ()
93 (decode-windows-environment
94 (alien-funcall (extern-alien "GetEnvironmentStrings"
95 (function system-area-pointer
))))))
97 ;;; Convert from a CMU CL representation of a Unix environment to a
98 ;;; SBCL representation.
99 (defun unix-environment-sbcl-from-cmucl (cmucl)
102 (destructuring-bind (key . val
) cons
103 (declare (type keyword key
) (string val
))
104 (concatenate 'simple-string
(symbol-name key
) "=" val
)))
107 ;;;; Import wait3(2) from Unix.
110 (define-alien-routine ("waitpid" c-waitpid
) int
116 (defun waitpid (pid &optional do-not-hang check-for-stopped
)
118 "Return any available status information on child process with PID."
119 (multiple-value-bind (pid status
)
121 (logior (if do-not-hang
124 (if check-for-stopped
127 (cond ((or (minusp pid
)
130 ((eql (ldb (byte 8 0) status
)
134 (ldb (byte 8 8) status
)))
135 ((zerop (ldb (byte 7 0) status
))
138 (ldb (byte 8 8) status
)))
140 (let ((signal (ldb (byte 7 0) status
)))
151 (not (zerop (ldb (byte 1 7) status
)))))))))
153 ;;;; process control stuff
154 (defvar *active-processes
* nil
156 "List of process structures for all active processes.")
158 (defvar *active-processes-lock
*
159 (sb-thread:make-mutex
:name
"Lock for active processes."))
161 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
162 ;;; mutex is needed. More importantly the sigchld signal handler also
163 ;;; accesses it, that's why we need without-interrupts.
164 (defmacro with-active-processes-lock
(() &body body
)
165 `(sb-thread::with-system-mutex
(*active-processes-lock
*)
168 (defstruct (process (:copier nil
))
169 pid
; PID of child process
170 %status
; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
171 %exit-code
; either exit code or signal
172 core-dumped
; T if a core image was dumped
173 #-win32 pty
; stream to child's pty, or NIL
174 input
; stream to child's input, or NIL
175 output
; stream from child's output, or NIL
176 error
; stream from child's error output, or NIL
177 status-hook
; closure to call when PROC changes status
178 plist
; a place for clients to stash things
179 cookie
) ; list of the number of pipes from the subproc
181 (defmethod print-object ((process process
) stream
)
182 (print-unreadable-object (process stream
:type t
)
183 (let ((status (process-status process
)))
184 (if (eq :exited status
)
185 (format stream
"~S ~S" status
(process-%exit-code process
))
186 (format stream
"~S ~S" (process-pid process
) status
)))
190 (setf (documentation 'process-p
'function
)
191 "T if OBJECT is a PROCESS, NIL otherwise.")
194 (setf (documentation 'process-pid
'function
) "The pid of the child process.")
197 (define-alien-routine ("GetExitCodeProcess" get-exit-code-process
)
199 (handle unsigned
) (exit-code unsigned
:out
))
201 (defun process-exit-code (process)
203 "Return the exit code of PROCESS."
204 (or (process-%exit-code process
)
205 (progn (get-processes-status-changes)
206 (process-%exit-code process
))))
208 (defun process-status (process)
210 "Return the current status of PROCESS. The result is one of :RUNNING,
211 :STOPPED, :EXITED, or :SIGNALED."
212 (get-processes-status-changes)
213 (process-%status process
))
216 (setf (documentation 'process-exit-code
'function
)
217 "The exit code or the signal of a stopped process.")
220 (setf (documentation 'process-core-dumped
'function
)
221 "T if a core image was dumped by the process.")
224 (setf (documentation 'process-pty
'function
)
225 "The pty stream of the process or NIL.")
228 (setf (documentation 'process-input
'function
)
229 "The input stream of the process or NIL.")
232 (setf (documentation 'process-output
'function
)
233 "The output stream of the process or NIL.")
236 (setf (documentation 'process-error
'function
)
237 "The error stream of the process or NIL.")
240 (setf (documentation 'process-status-hook
'function
)
241 "A function that is called when PROCESS changes its status.
242 The function is called with PROCESS as its only argument.")
245 (setf (documentation 'process-plist
'function
)
246 "A place for clients to stash things.")
248 (defun process-wait (process &optional check-for-stopped
)
250 "Wait for PROCESS to quit running for some reason. When
251 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
253 (declare (ignorable check-for-stopped
))
255 (let ((pid (process-pid process
)))
256 (when (and pid
(plusp pid
))
260 (with-local-interrupts
261 (sb-win32:wait-object-or-signal pid
))))))))
264 (case (process-status process
)
267 (when check-for-stopped
270 (when (zerop (car (process-cookie process
)))
272 (serve-all-events 1))
276 ;;; Find the current foreground process group id.
277 (defun find-current-foreground-process (proc)
278 (with-alien ((result int
))
281 (sb-unix:unix-ioctl
(fd-stream-fd (process-pty proc
))
283 (alien-sap (addr result
)))
285 (error "TIOCPGRP ioctl failed: ~S" (strerror error
)))
290 (defun process-kill (process signal
&optional
(whom :pid
))
292 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
293 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
294 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
295 currently in the foreground."
296 (let ((pid (ecase whom
297 ((:pid
:process-group
)
298 (process-pid process
))
300 (find-current-foreground-process process
)))))
305 (sb-unix:unix-killpg pid signal
))
307 (sb-unix:unix-kill pid signal
)))
310 ((and (eql pid
(process-pid process
))
311 (= signal sb-unix
:sigcont
))
312 (setf (process-%status process
) :running
)
313 (setf (process-%exit-code process
) nil
)
314 (when (process-status-hook process
)
315 (funcall (process-status-hook process
) process
))
320 (defun process-alive-p (process)
322 "Return T if PROCESS is still alive, NIL otherwise."
323 (let ((status (process-status process
)))
324 (if (or (eq status
:running
)
325 (eq status
:stopped
))
329 (defun process-close (process)
331 "Close all streams connected to PROCESS and stop maintaining the
333 (macrolet ((frob (stream abort
)
334 `(when ,stream
(close ,stream
:abort
,abort
))))
336 (frob (process-pty process
) t
) ; Don't FLUSH-OUTPUT to dead process,
337 (frob (process-input process
) t
) ; .. 'cause it will generate SIGPIPE.
338 (frob (process-output process
) nil
)
339 (frob (process-error process
) nil
))
340 ;; FIXME: Given that the status-slot is no longer updated,
341 ;; maybe it should be set to :CLOSED, or similar?
342 (with-active-processes-lock ()
343 (setf *active-processes
* (delete process
*active-processes
*)))
345 (let ((handle (shiftf (process-pid process
) nil
)))
346 (when (and handle
(plusp handle
))
347 (or (sb-win32:close-handle handle
)
348 (sb-win32::win32-error
'process-close
))))
351 (defun get-processes-status-changes ()
353 (with-active-processes-lock ()
354 (setf *active-processes
*
357 ;; Wait only on pids belonging to processes
358 ;; started by RUN-PROGRAM. There used to be a
359 ;; WAIT3 call here, but that makes direct
360 ;; WAIT, WAITPID usage impossible due to the
361 ;; race with the SIGCHLD signal handler.
362 (multiple-value-bind (pid what code core
)
363 (waitpid (process-pid proc
) t t
)
365 (setf (process-%status proc
) what
)
366 (setf (process-%exit-code proc
) code
)
367 (setf (process-core-dumped proc
) core
)
368 (when (process-status-hook proc
)
373 (let ((pid (process-pid proc
)))
375 (multiple-value-bind (ok code
)
376 (sb-win32::get-exit-code-process pid
)
377 (when (and (plusp ok
) (/= code
259))
378 (setf (process-%status proc
) :exited
379 (process-%exit-code proc
) code
)
380 (when (process-status-hook proc
)
383 *active-processes
*)))
384 ;; Can't call the hooks before all the processes have been deal
385 ;; with, as calling a hook may cause re-entry to
386 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using waitpid,
387 ;; but in the Windows implementation it would be deeply bad.
388 (dolist (proc exited
)
389 (let ((hook (process-status-hook proc
)))
391 (funcall hook proc
))))))
393 ;;;; RUN-PROGRAM and close friends
395 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
396 (defvar *close-on-error
* nil
)
398 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
399 (defvar *close-in-parent
* nil
)
401 ;;; list of handlers installed by RUN-PROGRAM. FIXME: nothing seems
404 (defvar *handlers-installed
* nil
)
406 ;;; Find an unused pty. Return three values: the file descriptor for
407 ;;; the master side of the pty, the file descriptor for the slave side
408 ;;; of the pty, and the name of the tty device for the slave side.
409 #-
(or win32 openbsd freebsd dragonfly
)
411 (define-alien-routine ptsname c-string
(fd int
))
412 (define-alien-routine grantpt boolean
(fd int
))
413 (define-alien-routine unlockpt boolean
(fd int
))
416 ;; First try to use the Unix98 pty api.
417 (let* ((master-name (coerce (format nil
"/dev/ptmx") 'base-string
))
418 (master-fd (sb-unix:unix-open master-name
419 (logior sb-unix
:o_rdwr
425 (let* ((slave-name (ptsname master-fd
))
426 (slave-fd (sb-unix:unix-open slave-name
427 (logior sb-unix
:o_rdwr
431 (return-from find-a-pty
435 (sb-unix:unix-close master-fd
))
436 (error "could not find a pty")))
437 ;; No dice, try using the old-school method.
438 (dolist (char '(#\p
#\q
))
440 (let* ((master-name (coerce (format nil
"/dev/pty~C~X" char digit
)
442 (master-fd (sb-unix:unix-open master-name
443 (logior sb-unix
:o_rdwr
447 (let* ((slave-name (coerce (format nil
"/dev/tty~C~X" char digit
)
449 (slave-fd (sb-unix:unix-open slave-name
450 (logior sb-unix
:o_rdwr
454 (return-from find-a-pty
458 (sb-unix:unix-close master-fd
))))))
459 (error "could not find a pty")))
461 #+(or openbsd freebsd dragonfly
)
463 (define-alien-routine openpty int
(amaster int
:out
) (aslave int
:out
)
464 (name (* char
)) (termp (* t
)) (winp (* t
)))
466 (with-alien ((name-buf (array char
#.path-max
)))
467 (multiple-value-bind (return-val master-fd slave-fd
)
468 (openpty (cast name-buf
(* char
)) nil nil
)
469 (if (zerop return-val
)
472 (sb-alien::c-string-to-string
(alien-sap name-buf
)
473 (sb-impl::default-external-format
)
475 (error "could not find a pty"))))))
478 (defun open-pty (pty cookie
&key
(external-format :default
))
483 (push master
*close-on-error
*)
484 (push slave
*close-in-parent
*)
486 (multiple-value-bind (new-fd errno
) (sb-unix:unix-dup master
)
488 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master
(strerror errno
)))
489 (push new-fd
*close-on-error
*)
490 (copy-descriptor-to-stream new-fd pty cookie external-format
)))
492 (make-fd-stream master
:input t
:output t
493 :external-format external-format
494 :element-type
:default
495 :dual-channel-p t
)))))
497 ;; Null terminate strings only C-side: otherwise we can run into
498 ;; A-T-S-L even for simple encodings like ASCII. Multibyte encodings
499 ;; may need more than a single byte of zeros; assume 4 byte is enough
502 (defmacro round-null-terminated-bytes-to-words
(n)
503 `(logandc2 (the sb-vm
:signed-word
(+ (the fixnum
,n
)
504 4 (1- sb-vm
:n-machine-word-bytes
)))
505 (1- sb-vm
:n-machine-word-bytes
)))
508 (defun string-list-to-c-strvec (string-list)
509 (let* (;; We need an extra for the null, and an extra 'cause exect
510 ;; clobbers argv[-1].
511 (vec-bytes (* sb-vm
:n-machine-word-bytes
(+ (length string-list
) 2)))
512 (octet-vector-list (mapcar (lambda (s)
513 (string-to-octets s
))
515 (string-bytes (reduce #'+ octet-vector-list
517 (round-null-terminated-bytes-to-words
519 (total-bytes (+ string-bytes vec-bytes
))
520 ;; Memory to hold the vector of pointers and all the strings.
521 (vec-sap (allocate-system-memory total-bytes
))
522 (string-sap (sap+ vec-sap vec-bytes
))
523 ;; Index starts from [1]!
524 (vec-index-offset sb-vm
:n-machine-word-bytes
))
525 (declare (sb-vm:signed-word vec-bytes
)
526 (sb-vm:word string-bytes total-bytes
)
527 (system-area-pointer vec-sap string-sap
))
528 (dolist (octets octet-vector-list
)
529 (declare (type (simple-array (unsigned-byte 8) (*)) octets
))
530 (let ((size (length octets
)))
532 (sb-kernel:copy-ub8-to-system-area octets
0 string-sap
0 size
)
534 (sb-kernel:system-area-ub8-fill
0 string-sap size
4)
535 ;; Put the pointer in the vector.
536 (setf (sap-ref-sap vec-sap vec-index-offset
) string-sap
)
537 ;; Advance string-sap for the next string.
538 (setf string-sap
(sap+ string-sap
539 (round-null-terminated-bytes-to-words size
)))
540 (incf vec-index-offset sb-vm
:n-machine-word-bytes
)))
541 ;; Final null pointer.
542 (setf (sap-ref-sap vec-sap vec-index-offset
) (int-sap 0))
543 (values vec-sap
(sap+ vec-sap sb-vm
:n-machine-word-bytes
) total-bytes
)))
546 (defmacro with-args
((var str-list
) &body body
)
547 (with-unique-names (sap size
)
548 `(multiple-value-bind (,sap
,var
,size
)
549 (string-list-to-c-strvec ,str-list
)
553 (deallocate-system-memory ,sap
,size
)))))
555 (defmacro with-environment
((var str-list
&key null
) &body body
)
556 (once-only ((null null
))
557 (with-unique-names (sap size
)
558 `(multiple-value-bind (,sap
,var
,size
)
560 (values nil
(int-sap 0))
561 #-win32
(string-list-to-c-strvec ,str-list
)
562 #+win32
(encode-windows-environment ,str-list
))
567 (deallocate-system-memory ,sap
,size
)))))))
569 (define-alien-routine spawn
583 (defun escape-arg (arg stream
)
584 ;; Normally, #\\ doesn't have to be escaped
585 ;; But if #\" follows #\\, then they have to be escaped.
586 ;; Do that by counting the number of consequent backslashes, and
587 ;; upon encoutering #\" immediately after them, output the same
588 ;; number of backslashes, plus one for #\"
589 (write-char #\" stream
)
590 (loop with slashes
= 0
591 for i below
(length arg
)
592 for previous-char
= #\a then char
593 for char
= (char arg i
)
598 do
(write-char #\\ stream
))
599 (write-string "\\\"" stream
))
601 (write-char char stream
)))
608 ;; The final #\" counts too, but doesn't need to be escaped itself
610 do
(write-char #\\ stream
)))
611 (write-char #\" stream
))
613 (defun prepare-args (args)
615 ((every #'simple-string-p args
)
619 (loop for arg in args
620 collect
(coerce arg
'simple-string
)))
623 (with-simple-output-to-string (str)
624 (loop for
(arg . rest
) on args
626 (cond ((find-if (lambda (c) (find c
'(#\Space
#\Tab
#\")))
628 (escape-arg arg str
))
632 (write-char #\Space str
)))))))
634 ;;; FIXME: There shouldn't be two semiredundant versions of the
635 ;;; documentation. Since this is a public extension function, the
636 ;;; documentation should be in the doc string. So all information from
637 ;;; this comment should be merged into the doc string, and then this
638 ;;; comment can go away.
640 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
641 ;;; Strange stuff happens to keep the Unix state of the world
644 ;;; The child process needs to get its input from somewhere, and send
645 ;;; its output (both standard and error) to somewhere. We have to do
646 ;;; different things depending on where these somewheres really are.
648 ;;; For input, there are five options:
649 ;;; -- T: Just leave fd 0 alone. Pretty simple.
650 ;;; -- "file": Read from the file. We need to open the file and
651 ;;; pull the descriptor out of the stream. The parent should close
652 ;;; this stream after the child is up and running to free any
653 ;;; storage used in the parent.
654 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
655 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
656 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
657 ;;; writeable descriptor, and pass the readable descriptor to
658 ;;; the child. The parent must close the readable descriptor for
659 ;;; EOF to be passed up correctly.
660 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
661 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
662 ;;; everything across.
664 ;;; For output, there are five options:
665 ;;; -- T: Leave descriptor 1 alone.
666 ;;; -- "file": dump output to the file.
667 ;;; -- NIL: dump output to /dev/null.
668 ;;; -- :STREAM: return a stream that can be read from.
669 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
670 ;;; Otherwise, copy stuff from output to stream.
672 ;;; For error, there are all the same options as output plus:
673 ;;; -- :OUTPUT: redirect to the same place as output.
675 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
676 ;;; the fork worked, and NIL if it did not.
677 (defun run-program (program args
682 (unix-environment-sbcl-from-cmucl env
))
688 if-input-does-not-exist
690 (if-output-exists :error
)
692 (if-error-exists :error
)
694 (external-format :default
)
699 ;; The Texinfoizer is sensitive to whitespace, so mind the
700 ;; placement of the #-win32 pseudosplicings.
701 "RUN-PROGRAM creates a new process specified by the PROGRAM
702 argument. ARGS are the standard arguments that can be passed to a
703 program. For no arguments, use NIL (which means that just the
704 name of the program is passed as arg 0).
706 The program arguments and the environment are encoded using the
707 default external format for streams.
709 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
710 Users Manual for details about the PROCESS structure.
712 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
714 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
715 programs, but unlike the original CMU CL implementation, copies
716 the Unix environment by default."#-win32
"
717 - Running Unix programs from a setuid process, or in any other
718 situation where the Unix environment is under the control of someone
719 else, is a mother lode of security problems. If you are contemplating
720 doing this, read about it first. (The Perl community has a lot of good
721 documentation about this and other security issues in script-like
724 The &KEY arguments have the following meanings:
726 a list of STRINGs describing the new Unix environment
727 (as in \"man environ\"). The default is to copy the environment of
730 an alternative lossy representation of the new Unix environment,
731 for compatibility with CMU CL
733 Look for PROGRAM in each of the directories in the child's $PATH
734 environment variable. Otherwise an absolute pathname is required.
736 If non-NIL (default), wait until the created process finishes. If
737 NIL, continue running Lisp until the program finishes."#-win32
"
739 Either T, NIL, or a stream. Unless NIL, the subprocess is established
740 under a PTY. If :pty is a stream, all output to this pty is sent to
741 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
742 connected to pty that can read output and write input.""
744 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
745 input for the current process is inherited. If NIL, "
746 #-win32
"/dev/null"#+win32
"nul""
747 is used. If a pathname, the file so specified is used. If a stream,
748 all the input is read from that stream and sent to the subprocess. If
749 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
750 its output to the process. Defaults to NIL.
751 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
753 :ERROR to generate an error
754 :CREATE to create an empty file
755 NIL (the default) to return NIL from RUN-PROGRAM
757 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
758 output for the current process is inherited. If NIL, "
759 #-win32
"/dev/null"#+win32
"nul""
760 is used. If a pathname, the file so specified is used. If a stream,
761 all the output from the process is written to this stream. If
762 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
763 be read to get the output. Defaults to NIL.
764 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
766 :ERROR (the default) to generate an error
767 :SUPERSEDE to supersede the file with output from the program
768 :APPEND to append output from the program to the file
769 NIL to return NIL from RUN-PROGRAM, without doing anything
770 :ERROR and :IF-ERROR-EXISTS
771 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
772 specified as :OUTPUT in which case all error output is routed to the
773 same place as normal output.
775 This is a function the system calls whenever the status of the
776 process changes. The function takes the process as an argument.
778 The external-format to use for :INPUT, :OUTPUT, and :ERROR :STREAMs.
780 Specifies the directory in which the program should be run.
781 NIL (the default) means the directory is unchanged.")
782 (when (and env-p environment-p
)
783 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
784 (let* (;; Clear various specials used by GET-DESCRIPTOR-FOR to
785 ;; communicate cleanup info.
788 ;; Some other binding used only on non-Win32. FIXME:
789 ;; nothing seems to set this.
790 #-win32
*handlers-installed
*
791 ;; Establish PROC at this level so that we can return it.
793 (progname (native-namestring program
))
794 (args (prepare-args (cons progname args
)))
795 (directory (and directory
(native-namestring directory
)))
799 ;; Note: despite the WITH-* names, these macros don't
800 ;; expand into UNWIND-PROTECT forms. They're just
801 ;; syntactic sugar to make the rest of the routine slightly
803 (macrolet ((with-fd-and-stream-for (((fd stream
) which
&rest args
)
805 `(multiple-value-bind (,fd
,stream
)
808 `(get-descriptor-for ,which
,@args
))
810 `(if (eq ,(first args
) :output
)
811 ;; kludge: we expand into
812 ;; hard-coded symbols here.
813 (values stdout output-stream
)
814 (get-descriptor-for ,which
,@args
))))
816 (return-from run-program
))
818 (with-open-pty (((pty-name pty-stream
) (pty cookie
))
820 (declare (ignorable pty-name pty-stream pty cookie
))
824 `(multiple-value-bind (,pty-name
,pty-stream
)
825 (open-pty ,pty
,cookie
:external-format external-format
)
827 (with-fd-and-stream-for ((stdin input-stream
) :input
830 :if-does-not-exist if-input-does-not-exist
831 :external-format external-format
833 (with-fd-and-stream-for ((stdout output-stream
) :output
836 :if-exists if-output-exists
837 :external-format external-format
)
838 (with-fd-and-stream-for ((stderr error-stream
) :error
841 :if-exists if-error-exists
842 :external-format external-format
)
843 (with-open-pty ((pty-name pty-stream
) (pty cookie
))
844 ;; Make sure we are not notified about the child
845 ;; death before we have installed the PROCESS
846 ;; structure in *ACTIVE-PROCESSES*.
848 (with-active-processes-lock ()
849 (with-environment (environment-vec environment
850 :null
(not (or environment environment-p
)))
853 (sb-win32::mswin-spawn
857 search environment-vec wait directory
)
859 (with-args (args-vec args
)
861 (spawn progname args-vec
864 environment-vec pty-name
865 (if wait
1 0) directory
))))
866 (unless (minusp child
)
870 :output output-stream
872 :status-hook status-hook
874 #-win32
:pty
#-win32 pty-stream
875 :%status
#-win32
:running
883 #+win32
:%exit-code
#+win32
(and wait child
)))
884 (push proc
*active-processes
*))))
885 ;; Report the error outside the lock.
888 (error "Couldn't fork child process: ~A"
891 (error "Couldn't execute ~S: ~A"
892 progname
(strerror)))
894 (error "Couldn't change directory to ~S: ~A"
895 directory
(strerror))))))))))
896 (dolist (fd *close-in-parent
*)
897 (sb-unix:unix-close fd
))
899 (dolist (fd *close-on-error
*)
900 (sb-unix:unix-close fd
))
902 (dolist (handler *handlers-installed
*)
903 (remove-fd-handler handler
)))
905 (when (and wait proc
)
908 (dolist (handler *handlers-installed
*)
909 (remove-fd-handler handler
)))))
912 ;;; Install a handler for any input that shows up on the file
913 ;;; descriptor. The handler reads the data and writes it to the
915 (defun copy-descriptor-to-stream (descriptor stream cookie external-format
)
918 (buf (make-array 256 :element-type
'(unsigned-byte 8)))
920 (et (stream-element-type stream
))
923 ((member et
'(character base-char
))
925 (let* ((decode-end read-end
)
926 (string (handler-case
929 :external-format external-format
)
930 (end-of-input-in-character (e)
932 (octet-decoding-error-start e
))
935 :external-format external-format
)))))
936 (unless (zerop (length string
))
937 (write-string string stream
)
938 (when (/= decode-end
(length buf
))
939 (replace buf buf
:start2 decode-end
:end2 read-end
))
940 (decf read-end decode-end
)))))
946 (error 'simple-type-error
948 "Error using ~s for program output:~@
953 (type-error-expected-type c
)
955 (type-error-datum c
)))))
956 (write-sequence buf stream
:end read-end
))
957 (setf read-end
0))))))
963 (declare (ignore fd
))
968 (result readable
/errno
)
969 (sb-unix:unix-select
(1+ descriptor
)
973 (if (eql sb-unix
:eintr readable
/errno
)
975 (error "~@<Couldn't select on sub-process: ~
977 (strerror readable
/errno
))))
980 (multiple-value-bind (count errno
)
981 (with-pinned-objects (buf)
982 (sb-unix:unix-read descriptor
983 (sap+ (vector-sap buf
) read-end
)
984 (- (length buf
) read-end
)))
986 ((and #-win32
(or (and (null count
)
987 (eql errno sb-unix
:eio
))
989 #+win32
(<= count
0))
990 (remove-fd-handler handler
)
993 (sb-unix:unix-close descriptor
)
994 (unless (zerop read-end
)
995 ;; Should this be an END-OF-FILE?
996 (error "~@<non-empty buffer when EOF reached ~
997 while reading from child: ~S~:>" buf
))
1000 (remove-fd-handler handler
)
1004 "~@<couldn't read input from sub-process: ~
1008 (incf read-end count
)
1009 (funcall copy-fun
))))))))
1011 (push handler
*handlers-installed
*)))
1013 ;;; FIXME: something very like this is done in SB-POSIX to treat
1014 ;;; streams as file descriptor designators; maybe we can combine these
1015 ;;; two? Additionally, as we have a couple of user-defined streams
1016 ;;; libraries, maybe we should have a generic function for doing this,
1017 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
1018 ;;; maybe also with SB-POSIX)?
1019 (defun get-stream-fd-and-external-format (stream direction
)
1022 (values (fd-stream-fd stream
) nil
(stream-external-format stream
)))
1024 (get-stream-fd-and-external-format
1025 (symbol-value (synonym-stream-symbol stream
)) direction
))
1029 (get-stream-fd-and-external-format
1030 (two-way-stream-input-stream stream
) direction
))
1032 (get-stream-fd-and-external-format
1033 (two-way-stream-output-stream stream
) direction
))))))
1035 (defun get-temporary-directory ()
1036 #-win32
(or (sb-ext:posix-getenv
"TMPDIR")
1038 #+win32
(or (sb-ext:posix-getenv
"TEMP")
1042 ;;; Find a file descriptor to use for object given the direction.
1043 ;;; Returns the descriptor. If object is :STREAM, returns the created
1044 ;;; stream as the second value.
1045 (defun get-descriptor-for (argument object cookie
1047 &key direction
(external-format :default
) wait
1049 (declare (ignore wait
)) ;This is explained below.
1050 ;; Our use of a temporary file dates back to very old CMUCLs, and
1051 ;; was probably only ever intended for use with STRING-STREAMs,
1052 ;; which are ordinarily smallish. However, as we've got
1053 ;; user-defined stream classes, we can end up trying to copy
1054 ;; arbitrarily much data into the temp file, and so are liable to
1055 ;; run afoul of disk quotas or to choke on small /tmp file systems.
1056 (labels ((fail (format &rest arguments
)
1057 (error "~s error processing ~s argument:~% ~?" 'run-program argument format arguments
))
1059 (multiple-value-bind (fd name
/errno
)
1060 (sb-unix:sb-mkstemp
(format nil
"~a/.run-program-XXXXXX"
1061 (get-temporary-directory))
1064 (fail "could not open a temporary file: ~A"
1065 (strerror name
/errno
)))
1066 ;; Can't unlink an open file on Windows
1068 (unless (sb-unix:unix-unlink name
/errno
)
1069 (sb-unix:unix-close fd
)
1070 (fail "failed to unlink ~A" name
/errno
))
1072 (let ((dev-null #.
(coerce #-win32
"/dev/null" #+win32
"nul" 'base-string
)))
1073 (cond ((eq object t
)
1074 ;; No new descriptor is needed.
1076 ((or (eq object nil
)
1077 (and (typep object
'broadcast-stream
)
1078 (not (broadcast-stream-streams object
))))
1080 (multiple-value-bind
1082 (sb-unix:unix-open dev-null
1084 (:input sb-unix
:o_rdonly
)
1085 (:output sb-unix
:o_wronly
)
1088 #+win32
:overlapped
#+win32 nil
)
1090 (fail "~@<couldn't open ~S: ~2I~_~A~:>"
1091 dev-null
(strerror errno
)))
1093 (setf (sb-win32::inheritable-handle-p fd
) t
)
1094 (push fd
*close-in-parent
*)
1096 ((eq object
:stream
)
1097 (multiple-value-bind (read-fd write-fd
) (sb-unix:unix-pipe
)
1099 (fail "couldn't create pipe: ~A" (strerror write-fd
)))
1101 (setf (sb-win32::inheritable-handle-p read-fd
)
1102 (eq direction
:input
)
1103 (sb-win32::inheritable-handle-p write-fd
)
1104 (eq direction
:output
))
1107 (push read-fd
*close-in-parent
*)
1108 (push write-fd
*close-on-error
*)
1109 (let ((stream (make-fd-stream write-fd
:output t
1110 :element-type
:default
1113 (values read-fd stream
)))
1115 (push read-fd
*close-on-error
*)
1116 (push write-fd
*close-in-parent
*)
1117 (let ((stream (make-fd-stream read-fd
:input t
1118 :element-type
:default
1121 (values write-fd stream
)))
1123 (sb-unix:unix-close read-fd
)
1124 (sb-unix:unix-close write-fd
)
1125 (fail "Direction must be either :INPUT or :OUTPUT, not ~S."
1127 ((or (pathnamep object
) (stringp object
))
1128 ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
1129 ;; than munge the &rest list for OPEN, just disable keyword
1130 ;; validation there.
1131 (with-open-stream (file (apply #'open object
1133 #+win32
:overlapped
#+win32 nil
1136 (multiple-value-bind
1138 (sb-unix:unix-dup
(fd-stream-fd file
))
1140 (push fd
*close-in-parent
*)
1143 (fail "couldn't duplicate file descriptor: ~A"
1144 (strerror errno
))))))))
1149 ;; If we can get an fd for the stream, let the child
1150 ;; process use the fd for its descriptor. Otherwise,
1151 ;; we copy data from the stream into a temp file, and
1152 ;; give the temp file's descriptor to the
1154 (multiple-value-bind (fd stream format
)
1155 (get-stream-fd-and-external-format object
:input
)
1156 (declare (ignore format
))
1158 (return (values fd stream
))))
1159 ;; FIXME: if we can't get the file descriptor, since
1160 ;; the stream might be interactive or otherwise
1161 ;; block-y, we can't know whether we can copy the
1162 ;; stream's data to a temp file, so if RUN-PROGRAM was
1163 ;; called with :WAIT NIL, we should probably error.
1164 ;; However, STRING-STREAMs aren't fd-streams, but
1165 ;; they're not prone to blocking; any user-defined
1166 ;; streams that "read" from some in-memory data will
1167 ;; probably be similar to STRING-STREAMs. So maybe we
1168 ;; should add a STREAM-INTERACTIVE-P generic function
1169 ;; for problems like this? Anyway, the machinery is
1170 ;; here, if you feel like filling in the details.
1172 (when (and (null wait
) #<some undetermined criterion
>)
1173 (error "~@<don't know how to get an fd for ~A, and so ~
1174 can't ensure that copying its data to the ~
1175 child process won't hang~:>" object
))
1177 (let ((fd (make-temp-fd))
1178 (et (stream-element-type object
)))
1179 (cond ((member et
'(character base-char
))
1181 (multiple-value-bind
1183 (read-line object nil nil
)
1186 (let ((vector (string-to-octets
1188 :external-format external-format
)))
1190 fd vector
0 (length vector
)))
1194 fd
#.
(string #\Newline
) 0 1)))))
1199 (error 'simple-type-error
1201 "Error using ~s for program input:~@
1206 (type-error-expected-type c
)
1208 (type-error-datum c
)))))
1209 (loop with buf
= (make-array 256 :element-type
'(unsigned-byte 8))
1210 for p
= (read-sequence buf object
)
1212 do
(sb-unix:unix-write fd buf
0 p
)))))
1213 (sb-unix:unix-lseek fd
0 sb-unix
:l_set
)
1214 (push fd
*close-in-parent
*)
1215 (return (values fd nil
)))))
1218 ;; Similar to the :input trick above, except we
1219 ;; arrange to copy data from the stream. This is
1220 ;; slightly saner than the input case, since we don't
1221 ;; buffer to a file, but I think we may still lose if
1222 ;; there's unflushed data in the stream buffer and we
1223 ;; give the file descriptor to the child.
1224 (multiple-value-bind (fd stream format
)
1225 (get-stream-fd-and-external-format object
:output
)
1226 (declare (ignore format
))
1228 (return (values fd stream
))))
1229 (multiple-value-bind (read-fd write-fd
)
1232 (fail "couldn't create pipe: ~S" (strerror write-fd
)))
1234 (setf (sb-win32::inheritable-handle-p write-fd
) t
)
1235 (copy-descriptor-to-stream read-fd object cookie
1237 (push read-fd
*close-on-error
*)
1238 (push write-fd
*close-in-parent
*)
1239 (return (values write-fd nil
)))))))
1241 (fail "invalid option: ~S" object
))))))