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 copiers
) ; list of sb-win32::io-copier
183 (defmethod print-object ((process process
) stream
)
184 (print-unreadable-object (process stream
:type t
)
185 (let ((status (process-status process
)))
186 (if (eq :exited status
)
187 (format stream
"~S ~S" status
(process-%exit-code process
))
188 (format stream
"~S ~S" (process-pid process
) status
)))
192 (define-alien-routine ("GetExitCodeProcess" get-exit-code-process
)
194 (handle unsigned
) (exit-code unsigned
:out
))
196 (defun process-exit-code (process)
198 "Return the exit code of PROCESS."
199 (or (process-%exit-code process
)
200 (progn (get-processes-status-changes)
201 (process-%exit-code process
))))
203 (defun process-status (process)
205 "Return the current status of PROCESS. The result is one of :RUNNING,
206 :STOPPED, :EXITED, or :SIGNALED."
207 (get-processes-status-changes)
208 (process-%status process
))
211 (setf (documentation 'process-exit-code
'function
)
212 "The exit code or the signal of a stopped process."
213 (documentation 'process-core-dumped
'function
)
214 "T if a core image was dumped by the process."
215 (documentation 'process-pty
'function
)
216 "The pty stream of the process or NIL."
217 (documentation 'process-input
'function
)
218 "The input stream of the process or NIL."
219 (documentation 'process-output
'function
)
220 "The output stream of the process or NIL."
221 (documentation 'process-error
'function
)
222 "The error stream of the process or NIL."
223 (documentation 'process-status-hook
'function
) "A function that is called when PROCESS changes its status.
224 The function is called with PROCESS as its only argument."
225 (documentation 'process-plist
'function
)
226 "A place for clients to stash things."
227 (documentation 'process-p
'function
)
228 "T if OBJECT is a PROCESS, NIL otherwise."
229 (documentation 'process-pid
'function
) "The pid of the child process.")
231 (defun process-wait (process &optional check-for-stopped
)
233 "Wait for PROCESS to quit running for some reason. When
234 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
236 (declare (ignorable check-for-stopped
))
238 (sb-win32::win32-process-wait process
)
241 (case (process-status process
)
244 (when check-for-stopped
247 (when (zerop (car (process-cookie process
)))
249 (serve-all-events 1))
253 ;;; Find the current foreground process group id.
254 (defun find-current-foreground-process (proc)
255 (with-alien ((result int
))
258 (sb-unix:unix-ioctl
(fd-stream-fd (process-pty proc
))
260 (alien-sap (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
*)))
322 (let ((handle (shiftf (process-pid process
) nil
)))
323 (when (and handle
(plusp handle
))
324 (or (sb-win32:close-handle handle
)
325 (sb-win32::win32-error
'process-close
))))
328 (defun get-processes-status-changes ()
330 (with-active-processes-lock ()
331 (setf *active-processes
*
334 ;; Wait only on pids belonging to processes
335 ;; started by RUN-PROGRAM. There used to be a
336 ;; WAIT3 call here, but that makes direct
337 ;; WAIT, WAITPID usage impossible due to the
338 ;; race with the SIGCHLD signal handler.
339 (multiple-value-bind (pid what code core
)
340 (waitpid (process-pid proc
) t t
)
342 (setf (process-%status proc
) what
)
343 (setf (process-%exit-code proc
) code
)
344 (setf (process-core-dumped proc
) core
)
345 (when (process-status-hook proc
)
350 (let ((pid (process-pid proc
)))
352 (multiple-value-bind (ok code
)
353 (sb-win32::get-exit-code-process pid
)
354 (when (and (plusp ok
)
355 (/= code sb-win32
::still-active
))
356 (setf (process-%status proc
) :exited
357 (process-%exit-code proc
) code
)
358 (when (process-status-hook proc
)
361 *active-processes
*)))
362 ;; Can't call the hooks before all the processes have been deal
363 ;; with, as calling a hook may cause re-entry to
364 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using waitpid,
365 ;; but in the Windows implementation it would be deeply bad.
366 (dolist (proc exited
)
367 (let ((hook (process-status-hook proc
)))
369 (funcall hook proc
))))))
371 ;;;; RUN-PROGRAM and close friends
373 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
374 (defvar *close-on-error
* nil
)
376 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
377 (defvar *close-in-parent
* nil
)
379 ;;; list of handlers installed by RUN-PROGRAM.
380 (defvar *handlers-installed
* nil
)
382 ;;; Find an unused pty. Return three values: the file descriptor for
383 ;;; the master side of the pty, the file descriptor for the slave side
384 ;;; of the pty, and the name of the tty device for the slave side.
385 #-
(or win32 openbsd freebsd dragonfly
)
387 (define-alien-routine ptsname c-string
(fd int
))
388 (define-alien-routine grantpt boolean
(fd int
))
389 (define-alien-routine unlockpt boolean
(fd int
))
392 ;; First try to use the Unix98 pty api.
393 (let* ((master-name (coerce (format nil
"/dev/ptmx") 'base-string
))
394 (master-fd (sb-unix:unix-open master-name
395 (logior sb-unix
:o_rdwr
401 (let* ((slave-name (ptsname master-fd
))
402 (slave-fd (sb-unix:unix-open slave-name
403 (logior sb-unix
:o_rdwr
407 (return-from find-a-pty
411 (sb-unix:unix-close master-fd
))
412 (error "could not find a pty")))
413 ;; No dice, try using the old-school method.
414 (dolist (char '(#\p
#\q
))
416 (let* ((master-name (coerce (format nil
"/dev/pty~C~X" char digit
)
418 (master-fd (sb-unix:unix-open master-name
419 (logior sb-unix
:o_rdwr
423 (let* ((slave-name (coerce (format nil
"/dev/tty~C~X" char digit
)
425 (slave-fd (sb-unix:unix-open slave-name
426 (logior sb-unix
:o_rdwr
430 (return-from find-a-pty
434 (sb-unix:unix-close master-fd
))))))
435 (error "could not find a pty")))
437 #+(or openbsd freebsd dragonfly
)
439 (define-alien-routine openpty int
(amaster int
:out
) (aslave int
:out
)
440 (name (* char
)) (termp (* t
)) (winp (* t
)))
442 (with-alien ((name-buf (array char
#.path-max
)))
443 (multiple-value-bind (return-val master-fd slave-fd
)
444 (openpty (cast name-buf
(* char
)) nil nil
)
445 (if (zerop return-val
)
448 (sb-alien::c-string-to-string
(alien-sap name-buf
)
449 (sb-impl::default-external-format
)
451 (error "could not find a pty"))))))
454 (defun open-pty (pty cookie
&key
(external-format :default
))
459 (push master
*close-on-error
*)
460 (push slave
*close-in-parent
*)
462 (multiple-value-bind (new-fd errno
) (sb-unix:unix-dup master
)
464 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master
(strerror errno
)))
465 (push new-fd
*close-on-error
*)
466 (copy-descriptor-to-stream new-fd pty cookie external-format
)))
468 (make-fd-stream master
:input t
:output t
469 :external-format external-format
470 :element-type
:default
471 :dual-channel-p t
)))))
473 ;; Null terminate strings only C-side: otherwise we can run into
474 ;; A-T-S-L even for simple encodings like ASCII. Multibyte encodings
475 ;; may need more than a single byte of zeros; assume 4 byte is enough
478 (defmacro round-null-terminated-bytes-to-words
(n)
479 `(logandc2 (the sb-vm
:signed-word
(+ (the fixnum
,n
)
480 4 (1- sb-vm
:n-machine-word-bytes
)))
481 (1- sb-vm
:n-machine-word-bytes
)))
484 (defun string-list-to-c-strvec (string-list)
485 (let* (;; We need an extra for the null, and an extra 'cause exect
486 ;; clobbers argv[-1].
487 (vec-bytes (* sb-vm
:n-machine-word-bytes
(+ (length string-list
) 2)))
488 (octet-vector-list (mapcar (lambda (s)
489 (string-to-octets s
))
491 (string-bytes (reduce #'+ octet-vector-list
493 (round-null-terminated-bytes-to-words
495 (total-bytes (+ string-bytes vec-bytes
))
496 ;; Memory to hold the vector of pointers and all the strings.
497 (vec-sap (allocate-system-memory total-bytes
))
498 (string-sap (sap+ vec-sap vec-bytes
))
499 ;; Index starts from [1]!
500 (vec-index-offset sb-vm
:n-machine-word-bytes
))
501 (declare (sb-vm:signed-word vec-bytes
)
502 (sb-vm:word string-bytes total-bytes
)
503 (system-area-pointer vec-sap string-sap
))
504 (dolist (octets octet-vector-list
)
505 (declare (type (simple-array (unsigned-byte 8) (*)) octets
))
506 (let ((size (length octets
)))
508 (sb-kernel:copy-ub8-to-system-area octets
0 string-sap
0 size
)
510 (sb-kernel:system-area-ub8-fill
0 string-sap size
4)
511 ;; Put the pointer in the vector.
512 (setf (sap-ref-sap vec-sap vec-index-offset
) string-sap
)
513 ;; Advance string-sap for the next string.
514 (setf string-sap
(sap+ string-sap
515 (round-null-terminated-bytes-to-words size
)))
516 (incf vec-index-offset sb-vm
:n-machine-word-bytes
)))
517 ;; Final null pointer.
518 (setf (sap-ref-sap vec-sap vec-index-offset
) (int-sap 0))
519 (values vec-sap
(sap+ vec-sap sb-vm
:n-machine-word-bytes
) total-bytes
)))
522 (defmacro with-args
((var str-list
) &body body
)
523 (with-unique-names (sap size
)
524 `(multiple-value-bind (,sap
,var
,size
)
525 (string-list-to-c-strvec ,str-list
)
529 (deallocate-system-memory ,sap
,size
)))))
531 (defmacro with-environment
((var str-list
&key null
) &body body
)
532 (once-only ((null null
))
533 (with-unique-names (sap size
)
534 `(multiple-value-bind (,sap
,var
,size
)
536 (values nil
(int-sap 0))
537 #-win32
(string-list-to-c-strvec ,str-list
)
538 #+win32
(encode-windows-environment ,str-list
))
543 (deallocate-system-memory ,sap
,size
)))))))
545 (define-alien-routine spawn
559 (defun escape-arg (arg stream
)
560 ;; Normally, #\\ doesn't have to be escaped
561 ;; But if #\" follows #\\, then they have to be escaped.
562 ;; Do that by counting the number of consequent backslashes, and
563 ;; upon encoutering #\" immediately after them, output the same
564 ;; number of backslashes, plus one for #\"
565 (write-char #\" stream
)
566 (loop with slashes
= 0
567 for i below
(length arg
)
568 for previous-char
= #\a then char
569 for char
= (char arg i
)
574 do
(write-char #\\ stream
))
575 (write-string "\\\"" stream
))
577 (write-char char stream
)))
584 ;; The final #\" counts too, but doesn't need to be escaped itself
586 do
(write-char #\\ stream
)))
587 (write-char #\" stream
))
589 (defun prepare-args (args)
591 ((every #'simple-string-p args
)
595 (loop for arg in args
596 collect
(coerce arg
'simple-string
)))
599 (with-simple-output-to-string (str)
600 (loop for
(arg . rest
) on args
602 (cond ((find-if (lambda (c) (find c
'(#\Space
#\Tab
#\")))
604 (escape-arg arg str
))
608 (write-char #\Space str
)))))))
610 ;;; FIXME: There shouldn't be two semiredundant versions of the
611 ;;; documentation. Since this is a public extension function, the
612 ;;; documentation should be in the doc string. So all information from
613 ;;; this comment should be merged into the doc string, and then this
614 ;;; comment can go away.
616 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
617 ;;; Strange stuff happens to keep the Unix state of the world
620 ;;; The child process needs to get its input from somewhere, and send
621 ;;; its output (both standard and error) to somewhere. We have to do
622 ;;; different things depending on where these somewheres really are.
624 ;;; For input, there are five options:
625 ;;; -- T: Just leave fd 0 alone. Pretty simple.
626 ;;; -- "file": Read from the file. We need to open the file and
627 ;;; pull the descriptor out of the stream. The parent should close
628 ;;; this stream after the child is up and running to free any
629 ;;; storage used in the parent.
630 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
631 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
632 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
633 ;;; writeable descriptor, and pass the readable descriptor to
634 ;;; the child. The parent must close the readable descriptor for
635 ;;; EOF to be passed up correctly.
636 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
637 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
638 ;;; everything across.
640 ;;; For output, there are five options:
641 ;;; -- T: Leave descriptor 1 alone.
642 ;;; -- "file": dump output to the file.
643 ;;; -- NIL: dump output to /dev/null.
644 ;;; -- :STREAM: return a stream that can be read from.
645 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
646 ;;; Otherwise, copy stuff from output to stream.
648 ;;; For error, there are all the same options as output plus:
649 ;;; -- :OUTPUT: redirect to the same place as output.
651 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
652 ;;; the fork worked, and NIL if it did not.
653 (defun run-program (program args
658 (unix-environment-sbcl-from-cmucl env
))
664 if-input-does-not-exist
666 (if-output-exists :error
)
668 (if-error-exists :error
)
670 (external-format :default
)
675 ;; The Texinfoizer is sensitive to whitespace, so mind the
676 ;; placement of the #-win32 pseudosplicings.
677 "RUN-PROGRAM creates a new process specified by the PROGRAM
678 argument. ARGS are the standard arguments that can be passed to a
679 program. For no arguments, use NIL (which means that just the
680 name of the program is passed as arg 0).
682 The program arguments and the environment are encoded using the
683 default external format for streams.
685 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
686 Users Manual for details about the PROCESS structure.
688 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
690 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
691 programs, but unlike the original CMU CL implementation, copies
692 the Unix environment by default."#-win32
"
693 - Running Unix programs from a setuid process, or in any other
694 situation where the Unix environment is under the control of someone
695 else, is a mother lode of security problems. If you are contemplating
696 doing this, read about it first. (The Perl community has a lot of good
697 documentation about this and other security issues in script-like
700 The &KEY arguments have the following meanings:
702 a list of STRINGs describing the new Unix environment
703 (as in \"man environ\"). The default is to copy the environment of
706 an alternative lossy representation of the new Unix environment,
707 for compatibility with CMU CL
709 Look for PROGRAM in each of the directories in the child's $PATH
710 environment variable. Otherwise an absolute pathname is required.
712 If non-NIL (default), wait until the created process finishes. If
713 NIL, continue running Lisp until the program finishes."#-win32
"
715 Either T, NIL, or a stream. Unless NIL, the subprocess is established
716 under a PTY. If :pty is a stream, all output to this pty is sent to
717 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
718 connected to pty that can read output and write input.""
720 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
721 input for the current process is inherited. If NIL, "
722 #-win32
"/dev/null"#+win32
"nul""
723 is used. If a pathname, the file so specified is used. If a stream,
724 all the input is read from that stream and sent to the subprocess. If
725 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
726 its output to the process. Defaults to NIL.
727 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
729 :ERROR to generate an error
730 :CREATE to create an empty file
731 NIL (the default) to return NIL from RUN-PROGRAM
733 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
734 output for the current process is inherited. If NIL, "
735 #-win32
"/dev/null"#+win32
"nul""
736 is used. If a pathname, the file so specified is used. If a stream,
737 all the output from the process is written to this stream. If
738 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
739 be read to get the output. Defaults to NIL.
740 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
742 :ERROR (the default) to generate an error
743 :SUPERSEDE to supersede the file with output from the program
744 :APPEND to append output from the program to the file
745 NIL to return NIL from RUN-PROGRAM, without doing anything
746 :ERROR and :IF-ERROR-EXISTS
747 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
748 specified as :OUTPUT in which case all error output is routed to the
749 same place as normal output.
751 This is a function the system calls whenever the status of the
752 process changes. The function takes the process as an argument.
754 The external-format to use for :INPUT, :OUTPUT, and :ERROR :STREAMs.
756 Specifies the directory in which the program should be run.
757 NIL (the default) means the directory is unchanged.")
758 (when (and env-p environment-p
)
759 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
760 (let* (;; Clear various specials used by GET-DESCRIPTOR-FOR to
761 ;; communicate cleanup info.
765 ;; Establish PROC at this level so that we can return it.
767 (progname (native-namestring program
))
768 (args (prepare-args (cons progname args
)))
769 (directory (and directory
(native-namestring directory
)))
773 ;; Note: despite the WITH-* names, these macros don't
774 ;; expand into UNWIND-PROTECT forms. They're just
775 ;; syntactic sugar to make the rest of the routine slightly
777 (macrolet ((with-fd-and-stream-for (((fd stream
) which
&rest args
)
779 `(multiple-value-bind (,fd
,stream
)
782 `(get-descriptor-for ,which
,@args
))
784 `(if (eq ,(first args
) :output
)
785 ;; kludge: we expand into
786 ;; hard-coded symbols here.
787 (values stdout output-stream
)
788 (get-descriptor-for ,which
,@args
))))
790 (return-from run-program
))
792 (with-open-pty (((pty-name pty-stream
) (pty cookie
))
794 (declare (ignorable pty-name pty-stream pty cookie
))
798 `(multiple-value-bind (,pty-name
,pty-stream
)
799 (open-pty ,pty
,cookie
:external-format external-format
)
801 (with-fd-and-stream-for ((stdin input-stream
) :input
804 :if-does-not-exist if-input-does-not-exist
805 :external-format external-format
807 (with-fd-and-stream-for ((stdout output-stream
) :output
810 :if-exists if-output-exists
811 :external-format external-format
)
812 (with-fd-and-stream-for ((stderr error-stream
) :error
815 :if-exists if-error-exists
816 :external-format external-format
)
817 (with-open-pty ((pty-name pty-stream
) (pty cookie
))
818 ;; Make sure we are not notified about the child
819 ;; death before we have installed the PROCESS
820 ;; structure in *ACTIVE-PROCESSES*.
822 (with-active-processes-lock ()
823 (with-environment (environment-vec environment
824 :null
(not (or environment environment-p
)))
827 (sb-win32::mswin-spawn
831 search environment-vec wait directory
)
833 (with-args (args-vec args
)
835 (spawn progname args-vec
838 environment-vec pty-name
839 (if wait
1 0) directory
))))
840 (unless (minusp child
)
844 :output output-stream
846 :status-hook status-hook
848 #-win32
:pty
#-win32 pty-stream
851 #+win32
:copiers
#+win32
*handlers-installed
*))
852 (push proc
*active-processes
*))))
853 ;; Report the error outside the lock.
856 (error "Couldn't fork child process: ~A"
859 (error "Couldn't execute ~S: ~A"
860 progname
(strerror)))
862 (error "Couldn't change directory to ~S: ~A"
863 directory
(strerror))))))))))
864 (dolist (fd *close-in-parent
*)
865 (sb-unix:unix-close fd
))
867 (dolist (fd *close-on-error
*)
868 (sb-unix:unix-close fd
))
870 (dolist (handler *handlers-installed
*)
871 (remove-fd-handler handler
)))
872 (when (and wait proc
)
876 (dolist (handler *handlers-installed
*)
877 (remove-fd-handler handler
)))))
880 ;;; Install a handler for any input that shows up on the file
881 ;;; descriptor. The handler reads the data and writes it to the
884 (defun copy-descriptor-to-stream (descriptor stream cookie external-format
)
887 (buf (make-array 256 :element-type
'(unsigned-byte 8)))
889 (et (stream-element-type stream
))
892 ((member et
'(character base-char
))
894 (let* ((decode-end read-end
)
895 (string (handler-case
898 :external-format external-format
)
899 (end-of-input-in-character (e)
901 (octet-decoding-error-start e
))
904 :external-format external-format
)))))
905 (unless (zerop (length string
))
906 (write-string string stream
)
907 (when (/= decode-end
(length buf
))
908 (replace buf buf
:start2 decode-end
:end2 read-end
))
909 (decf read-end decode-end
)))))
915 (error 'simple-type-error
917 "Error using ~s for program output:~@
922 (type-error-expected-type c
)
924 (type-error-datum c
)))))
925 (write-sequence buf stream
:end read-end
))
926 (setf read-end
0))))))
932 (declare (ignore fd
))
937 (result readable
/errno
)
938 (sb-unix:unix-select
(1+ descriptor
)
942 (if (eql sb-unix
:eintr readable
/errno
)
944 (error "~@<Couldn't select on sub-process: ~
946 (strerror readable
/errno
))))
949 (multiple-value-bind (count errno
)
950 (with-pinned-objects (buf)
951 (sb-unix:unix-read descriptor
952 (sap+ (vector-sap buf
) read-end
)
953 (- (length buf
) read-end
)))
955 ((and #-win32
(or (and (null count
)
956 (eql errno sb-unix
:eio
))
958 #+win32
(<= count
0))
959 (remove-fd-handler handler
)
962 (sb-unix:unix-close descriptor
)
963 (unless (zerop read-end
)
964 ;; Should this be an END-OF-FILE?
965 (error "~@<non-empty buffer when EOF reached ~
966 while reading from child: ~S~:>" buf
))
969 (remove-fd-handler handler
)
973 "~@<couldn't read input from sub-process: ~
977 (incf read-end count
)
978 (funcall copy-fun
))))))))
979 (push handler
*handlers-installed
*)))
982 (defun copy-descriptor-to-stream (descriptor stream cookie external-format
)
983 (declare (ignore cookie
))
984 (push (sb-win32::make-io-copier
:pipe descriptor
986 :external-format external-format
)
987 *handlers-installed
*))
989 ;;; FIXME: something very like this is done in SB-POSIX to treat
990 ;;; streams as file descriptor designators; maybe we can combine these
991 ;;; two? Additionally, as we have a couple of user-defined streams
992 ;;; libraries, maybe we should have a generic function for doing this,
993 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
994 ;;; maybe also with SB-POSIX)?
995 (defun get-stream-fd-and-external-format (stream direction
)
998 (values (fd-stream-fd stream
) nil
(stream-external-format stream
)))
1000 (get-stream-fd-and-external-format
1001 (symbol-value (synonym-stream-symbol stream
)) direction
))
1005 (get-stream-fd-and-external-format
1006 (two-way-stream-input-stream stream
) direction
))
1008 (get-stream-fd-and-external-format
1009 (two-way-stream-output-stream stream
) direction
))))))
1011 (defun get-temporary-directory ()
1012 #-win32
(or (sb-ext:posix-getenv
"TMPDIR")
1014 #+win32
(or (sb-ext:posix-getenv
"TEMP")
1018 ;;; Find a file descriptor to use for object given the direction.
1019 ;;; Returns the descriptor. If object is :STREAM, returns the created
1020 ;;; stream as the second value.
1021 (defun get-descriptor-for (argument object cookie
1023 &key direction
(external-format :default
) wait
1025 (declare (ignore wait
)) ;This is explained below.
1026 ;; Our use of a temporary file dates back to very old CMUCLs, and
1027 ;; was probably only ever intended for use with STRING-STREAMs,
1028 ;; which are ordinarily smallish. However, as we've got
1029 ;; user-defined stream classes, we can end up trying to copy
1030 ;; arbitrarily much data into the temp file, and so are liable to
1031 ;; run afoul of disk quotas or to choke on small /tmp file systems.
1032 (labels ((fail (format &rest arguments
)
1033 (error "~s error processing ~s argument:~% ~?" 'run-program argument format arguments
))
1035 (multiple-value-bind (fd name
/errno
)
1036 (sb-unix:sb-mkstemp
(format nil
"~a/.run-program-XXXXXX"
1037 (get-temporary-directory))
1040 (fail "could not open a temporary file: ~A"
1041 (strerror name
/errno
)))
1043 (setf (sb-win32::inheritable-handle-p fd
) t
)
1044 ;; Can't unlink an open file on Windows
1046 (unless (sb-unix:unix-unlink name
/errno
)
1047 (sb-unix:unix-close fd
)
1048 (fail "failed to unlink ~A" name
/errno
))
1050 (let ((dev-null #.
(coerce #-win32
"/dev/null" #+win32
"nul" 'base-string
)))
1051 (cond ((eq object t
)
1052 ;; No new descriptor is needed.
1054 ((or (eq object nil
)
1055 (and (typep object
'broadcast-stream
)
1056 (not (broadcast-stream-streams object
))))
1058 (multiple-value-bind
1060 (sb-unix:unix-open dev-null
1062 (:input sb-unix
:o_rdonly
)
1063 (:output sb-unix
:o_wronly
)
1066 #+win32
:overlapped
#+win32 nil
)
1068 (fail "~@<couldn't open ~S: ~2I~_~A~:>"
1069 dev-null
(strerror errno
)))
1071 (setf (sb-win32::inheritable-handle-p fd
) t
)
1072 (push fd
*close-in-parent
*)
1074 ((eq object
:stream
)
1075 (multiple-value-bind (read-fd write-fd
) (sb-unix:unix-pipe
)
1077 (fail "couldn't create pipe: ~A" (strerror write-fd
)))
1079 (setf (sb-win32::inheritable-handle-p read-fd
)
1080 (eq direction
:input
)
1081 (sb-win32::inheritable-handle-p write-fd
)
1082 (eq direction
:output
))
1085 (push read-fd
*close-in-parent
*)
1086 (push write-fd
*close-on-error
*)
1087 (let ((stream (make-fd-stream write-fd
:output t
1088 :element-type
:default
1091 (values read-fd stream
)))
1093 (push read-fd
*close-on-error
*)
1094 (push write-fd
*close-in-parent
*)
1095 (let ((stream (make-fd-stream read-fd
:input t
1096 :element-type
:default
1099 (values write-fd stream
)))
1101 (sb-unix:unix-close read-fd
)
1102 (sb-unix:unix-close write-fd
)
1103 (fail "Direction must be either :INPUT or :OUTPUT, not ~S."
1105 ((or (pathnamep object
) (stringp object
))
1106 ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
1107 ;; than munge the &rest list for OPEN, just disable keyword
1108 ;; validation there.
1109 (with-open-stream (file (apply #'open object
1111 #+win32
:overlapped
#+win32 nil
1114 (multiple-value-bind
1116 (sb-unix:unix-dup
(fd-stream-fd file
))
1118 (push fd
*close-in-parent
*)
1121 (fail "couldn't duplicate file descriptor: ~A"
1122 (strerror errno
))))))))
1127 ;; If we can get an fd for the stream, let the child
1128 ;; process use the fd for its descriptor. Otherwise,
1129 ;; we copy data from the stream into a temp file, and
1130 ;; give the temp file's descriptor to the
1132 (multiple-value-bind (fd stream format
)
1133 (get-stream-fd-and-external-format object
:input
)
1134 (declare (ignore format
))
1136 (return (values fd stream
))))
1137 ;; FIXME: if we can't get the file descriptor, since
1138 ;; the stream might be interactive or otherwise
1139 ;; block-y, we can't know whether we can copy the
1140 ;; stream's data to a temp file, so if RUN-PROGRAM was
1141 ;; called with :WAIT NIL, we should probably error.
1142 ;; However, STRING-STREAMs aren't fd-streams, but
1143 ;; they're not prone to blocking; any user-defined
1144 ;; streams that "read" from some in-memory data will
1145 ;; probably be similar to STRING-STREAMs. So maybe we
1146 ;; should add a STREAM-INTERACTIVE-P generic function
1147 ;; for problems like this? Anyway, the machinery is
1148 ;; here, if you feel like filling in the details.
1150 (when (and (null wait
) #<some undetermined criterion
>)
1151 (error "~@<don't know how to get an fd for ~A, and so ~
1152 can't ensure that copying its data to the ~
1153 child process won't hang~:>" object
))
1155 (let ((fd (make-temp-fd))
1156 (et (stream-element-type object
)))
1157 (cond ((member et
'(character base-char
))
1159 (multiple-value-bind
1161 (read-line object nil nil
)
1164 (let ((vector (string-to-octets
1166 :external-format external-format
)))
1168 fd vector
0 (length vector
)))
1172 fd
#.
(string #\Newline
) 0 1)))))
1177 (error 'simple-type-error
1179 "Error using ~s for program input:~@
1184 (type-error-expected-type c
)
1186 (type-error-datum c
)))))
1187 (loop with buf
= (make-array 256 :element-type
'(unsigned-byte 8))
1188 for p
= (read-sequence buf object
)
1190 do
(sb-unix:unix-write fd buf
0 p
)))))
1191 (sb-unix:unix-lseek fd
0 sb-unix
:l_set
)
1192 (push fd
*close-in-parent
*)
1193 (return (values fd nil
)))))
1196 ;; Similar to the :input trick above, except we
1197 ;; arrange to copy data from the stream. This is
1198 ;; slightly saner than the input case, since we don't
1199 ;; buffer to a file, but I think we may still lose if
1200 ;; there's unflushed data in the stream buffer and we
1201 ;; give the file descriptor to the child.
1202 (multiple-value-bind (fd stream format
)
1203 (get-stream-fd-and-external-format object
:output
)
1204 (declare (ignore format
))
1206 (return (values fd stream
))))
1207 (multiple-value-bind (read-fd write-fd
)
1208 #-win32
(sb-unix:unix-pipe
)
1209 #+win32
(sb-win32::make-named-pipe
)
1211 (fail "couldn't create pipe: ~S" (strerror write-fd
)))
1213 (setf (sb-win32::inheritable-handle-p write-fd
) t
)
1214 (copy-descriptor-to-stream read-fd object cookie
1216 (push read-fd
*close-on-error
*)
1217 (push write-fd
*close-in-parent
*)
1218 (return (values write-fd nil
)))))))
1220 (fail "invalid option: ~S" object
))))))