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))))
57 (defun decode-windows-environment (environment)
58 (loop until (zerop (sap-ref-8 environment 0))
60 (let ((string (sb-alien::c-string-to-string environment
61 (sb-alien::default-c-string-external-format)
63 (loop for value = (sap-ref-8 environment 0)
64 do (setf environment (sap+ environment 1))
68 (defun encode-windows-environment (list)
69 (let* ((external-format (sb-alien::default-c-string-external-format))
71 (length 1)) ;; 1 for \0 at the very end
75 (string-to-octets x :external-format external-format
79 (incf length (length octet))))
80 (let ((mem (allocate-system-memory length))
83 (loop for string in octets
84 for length = (length string)
86 (copy-ub8-to-system-area string 0 mem index length)
88 (setf (sap-ref-8 mem index) 0)
89 (values mem mem length))))
91 (defun posix-environ ()
92 (decode-windows-environment
93 (alien-funcall (extern-alien "GetEnvironmentStrings"
94 (function system-area-pointer))))))
96 ;;; Convert as best we can from an SBCL representation of a Unix
97 ;;; environment to a CMU CL representation.
99 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
101 ;;; smashing case of "Bletch=fub" in conversion to CMU-CL-style
102 ;;; environment alist
104 ;;; no #\= in "Noggin", eliding it in CMU-CL-style environment alist
105 ;;; ((:BLETCH . "fub") (:YES . "No!"))
106 (defun unix-environment-cmucl-from-sbcl (sbcl)
109 (declare (string string))
110 (let ((=-pos (position #\= string :test #'equal)))
113 (let* ((key-as-string (subseq string 0 =-pos))
114 (key-as-upcase-string (string-upcase key-as-string))
115 (key (keywordicate key-as-upcase-string))
116 (val (subseq string (1+ =-pos))))
117 (unless (string= key-as-string key-as-upcase-string)
118 (warn "smashing case of ~S in conversion to CMU-CL-style ~
122 (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
126 ;;; Convert from a CMU CL representation of a Unix environment to a
127 ;;; SBCL representation.
128 (defun unix-environment-sbcl-from-cmucl (cmucl)
131 (destructuring-bind (key . val) cons
132 (declare (type keyword key) (string val))
133 (concatenate 'simple-string (symbol-name key) "=" val)))
136 ;;;; Import wait3(2) from Unix.
139 (define-alien-routine ("waitpid" c-waitpid) sb-alien:int
141 (status sb-alien:int :out)
142 (options sb-alien:int))
145 (defun waitpid (pid &optional do-not-hang check-for-stopped)
147 "Return any available status information on child process with PID."
148 (multiple-value-bind (pid status)
150 (logior (if do-not-hang
153 (if check-for-stopped
156 (cond ((or (minusp pid)
159 ((eql (ldb (byte 8 0) status)
163 (ldb (byte 8 8) status)))
164 ((zerop (ldb (byte 7 0) status))
167 (ldb (byte 8 8) status)))
169 (let ((signal (ldb (byte 7 0) status)))
180 (not (zerop (ldb (byte 1 7) status)))))))))
182 ;;;; process control stuff
183 (defvar *active-processes* nil
185 "List of process structures for all active processes.")
187 (defvar *active-processes-lock*
188 (sb-thread:make-mutex :name "Lock for active processes."))
190 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
191 ;;; mutex is needed. More importantly the sigchld signal handler also
192 ;;; accesses it, that's why we need without-interrupts.
193 (defmacro with-active-processes-lock (() &body body)
194 `(sb-thread::with-system-mutex (*active-processes-lock*)
197 (defstruct (process (:copier nil))
198 pid ; PID of child process
199 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
200 %exit-code ; either exit code or signal
201 core-dumped ; T if a core image was dumped
202 #-win32 pty ; stream to child's pty, or NIL
203 input ; stream to child's input, or NIL
204 output ; stream from child's output, or NIL
205 error ; stream from child's error output, or NIL
206 status-hook ; closure to call when PROC changes status
207 plist ; a place for clients to stash things
208 cookie) ; list of the number of pipes from the subproc
210 (defmethod print-object ((process process) stream)
211 (print-unreadable-object (process stream :type t)
212 (let ((status (process-status process)))
213 (if (eq :exited status)
214 (format stream "~S ~S" status (process-%exit-code process))
215 (format stream "~S ~S" (process-pid process) status)))
219 (setf (documentation 'process-p 'function)
220 "T if OBJECT is a PROCESS, NIL otherwise.")
223 (setf (documentation 'process-pid 'function) "The pid of the child process.")
226 (define-alien-routine ("GetExitCodeProcess" get-exit-code-process)
228 (handle unsigned) (exit-code unsigned :out))
230 (defun process-exit-code (process)
232 "Return the exit code of PROCESS."
233 (or (process-%exit-code process)
234 (progn (get-processes-status-changes)
235 (process-%exit-code process))))
237 (defun process-status (process)
239 "Return the current status of PROCESS. The result is one of :RUNNING,
240 :STOPPED, :EXITED, or :SIGNALED."
241 (get-processes-status-changes)
242 (process-%status process))
245 (setf (documentation 'process-exit-code 'function)
246 "The exit code or the signal of a stopped process.")
249 (setf (documentation 'process-core-dumped 'function)
250 "T if a core image was dumped by the process.")
253 (setf (documentation 'process-pty 'function)
254 "The pty stream of the process or NIL.")
257 (setf (documentation 'process-input 'function)
258 "The input stream of the process or NIL.")
261 (setf (documentation 'process-output 'function)
262 "The output stream of the process or NIL.")
265 (setf (documentation 'process-error 'function)
266 "The error stream of the process or NIL.")
269 (setf (documentation 'process-status-hook 'function)
270 "A function that is called when PROCESS changes its status.
271 The function is called with PROCESS as its only argument.")
274 (setf (documentation 'process-plist 'function)
275 "A place for clients to stash things.")
277 (defun process-wait (process &optional check-for-stopped)
279 "Wait for PROCESS to quit running for some reason. When
280 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
282 (declare (ignorable check-for-stopped))
284 (let ((pid (process-pid process)))
285 (when (and pid (plusp pid))
289 (with-local-interrupts
290 (sb-win32:wait-object-or-signal pid))))))))
293 (case (process-status process)
296 (when check-for-stopped
299 (when (zerop (car (process-cookie process)))
301 (serve-all-events 1))
305 ;;; Find the current foreground process group id.
306 (defun find-current-foreground-process (proc)
307 (with-alien ((result sb-alien:int))
310 (sb-unix:unix-ioctl (fd-stream-fd (process-pty proc))
312 (alien-sap (sb-alien:addr result)))
314 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
319 (defun process-kill (process signal &optional (whom :pid))
321 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
322 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
323 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
324 currently in the foreground."
325 (let ((pid (ecase whom
326 ((:pid :process-group)
327 (process-pid process))
329 (find-current-foreground-process process)))))
334 (sb-unix:unix-killpg pid signal))
336 (sb-unix:unix-kill pid signal)))
339 ((and (eql pid (process-pid process))
340 (= signal sb-unix:sigcont))
341 (setf (process-%status process) :running)
342 (setf (process-%exit-code process) nil)
343 (when (process-status-hook process)
344 (funcall (process-status-hook process) process))
349 (defun process-alive-p (process)
351 "Return T if PROCESS is still alive, NIL otherwise."
352 (let ((status (process-status process)))
353 (if (or (eq status :running)
354 (eq status :stopped))
358 (defun process-close (process)
360 "Close all streams connected to PROCESS and stop maintaining the
362 (macrolet ((frob (stream abort)
363 `(when ,stream (close ,stream :abort ,abort))))
365 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process,
366 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
367 (frob (process-output process) nil)
368 (frob (process-error process) nil))
369 ;; FIXME: Given that the status-slot is no longer updated,
370 ;; maybe it should be set to :CLOSED, or similar?
371 (with-active-processes-lock ()
372 (setf *active-processes* (delete process *active-processes*)))
374 (let ((handle (shiftf (process-pid process) nil)))
375 (when (and handle (plusp handle))
376 (or (sb-win32:close-handle handle)
377 (sb-win32::win32-error 'process-close))))
380 (defun get-processes-status-changes ()
382 (with-active-processes-lock ()
383 (setf *active-processes*
386 ;; Wait only on pids belonging to processes
387 ;; started by RUN-PROGRAM. There used to be a
388 ;; WAIT3 call here, but that makes direct
389 ;; WAIT, WAITPID usage impossible due to the
390 ;; race with the SIGCHLD signal handler.
391 (multiple-value-bind (pid what code core)
392 (waitpid (process-pid proc) t t)
394 (setf (process-%status proc) what)
395 (setf (process-%exit-code proc) code)
396 (setf (process-core-dumped proc) core)
397 (when (process-status-hook proc)
402 (let ((pid (process-pid proc)))
404 (multiple-value-bind (ok code)
405 (sb-win32::get-exit-code-process pid)
406 (when (and (plusp ok) (/= code 259))
407 (setf (process-%status proc) :exited
408 (process-%exit-code proc) code)
409 (when (process-status-hook proc)
412 *active-processes*)))
413 ;; Can't call the hooks before all the processes have been deal
414 ;; with, as calling a hook may cause re-entry to
415 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using waitpid,
416 ;; but in the Windows implementation it would be deeply bad.
417 (dolist (proc exited)
418 (let ((hook (process-status-hook proc)))
420 (funcall hook proc))))))
422 ;;;; RUN-PROGRAM and close friends
424 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
425 (defvar *close-on-error* nil)
427 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
428 (defvar *close-in-parent* nil)
430 ;;; list of handlers installed by RUN-PROGRAM. FIXME: nothing seems
433 (defvar *handlers-installed* nil)
435 ;;; Find an unused pty. Return three values: the file descriptor for
436 ;;; the master side of the pty, the file descriptor for the slave side
437 ;;; of the pty, and the name of the tty device for the slave side.
440 (define-alien-routine ptsname c-string (fd int))
441 (define-alien-routine grantpt boolean (fd int))
442 (define-alien-routine unlockpt boolean (fd int))
445 ;; First try to use the Unix98 pty api.
446 (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
447 (master-fd (sb-unix:unix-open master-name
448 (logior sb-unix:o_rdwr
454 (let* ((slave-name (ptsname master-fd))
455 (slave-fd (sb-unix:unix-open slave-name
456 (logior sb-unix:o_rdwr
460 (return-from find-a-pty
464 (sb-unix:unix-close master-fd))
465 (error "could not find a pty")))
466 ;; No dice, try using the old-school method.
467 (dolist (char '(#\p #\q))
469 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
471 (master-fd (sb-unix:unix-open master-name
472 (logior sb-unix:o_rdwr
476 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
478 (slave-fd (sb-unix:unix-open slave-name
479 (logior sb-unix:o_rdwr
483 (return-from find-a-pty
487 (sb-unix:unix-close master-fd))))))
488 (error "could not find a pty")))
491 (define-alien-routine openpty int (amaster int :out) (aslave int :out)
492 (name (* char)) (termp (* t)) (winp (* t)))
494 (with-alien ((name-buf (array char 16)))
495 (multiple-value-bind (return-val master-fd slave-fd)
496 (openpty (cast name-buf (* char)) nil nil)
497 (if (zerop return-val)
500 (sb-alien::c-string-to-string (alien-sap name-buf)
501 (sb-impl::default-external-format)
503 (error "could not find a pty"))))))
506 (defun open-pty (pty cookie &key (external-format :default))
511 (push master *close-on-error*)
512 (push slave *close-in-parent*)
514 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
516 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
517 (push new-fd *close-on-error*)
518 (copy-descriptor-to-stream new-fd pty cookie external-format)))
520 (make-fd-stream master :input t :output t
521 :external-format external-format
522 :element-type :default
523 :dual-channel-p t)))))
525 ;; Null terminate strings only C-side: otherwise we can run into
526 ;; A-T-S-L even for simple encodings like ASCII. Multibyte encodings
527 ;; may need more than a single byte of zeros; assume 4 byte is enough
529 (defmacro round-null-terminated-bytes-to-words (n)
530 (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
531 `(logandc2 (the sb-vm:signed-word (+ (the fixnum ,n)
532 4 (1- ,bytes-per-word)))
533 (1- ,bytes-per-word))))
535 (defun string-list-to-c-strvec (string-list)
536 (let* (;; We need an extra for the null, and an extra 'cause exect
537 ;; clobbers argv[-1].
538 (vec-bytes (* sb-vm:n-word-bytes (+ (length string-list) 2)))
539 (octet-vector-list (mapcar (lambda (s)
540 (string-to-octets s))
542 (string-bytes (reduce #'+ octet-vector-list
544 (round-null-terminated-bytes-to-words
546 (total-bytes (+ string-bytes vec-bytes))
547 ;; Memory to hold the vector of pointers and all the strings.
548 (vec-sap (allocate-system-memory total-bytes))
549 (string-sap (sap+ vec-sap vec-bytes))
550 ;; Index starts from [1]!
551 (vec-index-offset sb-vm:n-word-bytes))
552 (declare (sb-vm:signed-word vec-bytes)
553 (sb-vm:word string-bytes total-bytes)
554 (system-area-pointer vec-sap string-sap))
555 (dolist (octets octet-vector-list)
556 (declare (type (simple-array (unsigned-byte 8) (*)) octets))
557 (let ((size (length octets)))
559 (sb-kernel:copy-ub8-to-system-area octets 0 string-sap 0 size)
561 (sb-kernel:system-area-ub8-fill 0 string-sap size 4)
562 ;; Put the pointer in the vector.
563 (setf (sap-ref-sap vec-sap vec-index-offset) string-sap)
564 ;; Advance string-sap for the next string.
565 (setf string-sap (sap+ string-sap
566 (round-null-terminated-bytes-to-words size)))
567 (incf vec-index-offset sb-vm:n-word-bytes)))
568 ;; Final null pointer.
569 (setf (sap-ref-sap vec-sap vec-index-offset) (int-sap 0))
570 (values vec-sap (sap+ vec-sap sb-vm:n-word-bytes) total-bytes)))
572 (defmacro with-c-strvec ((var str-list &key null) &body body)
573 (once-only ((null null))
574 (with-unique-names (sap size)
575 `(multiple-value-bind (,sap ,var ,size)
577 (values nil (int-sap 0))
578 (string-list-to-c-strvec ,str-list))
583 (deallocate-system-memory ,sap ,size)))))))
585 (defmacro with-environment ((var str-list &key null) &body body)
586 (once-only ((null null))
587 (with-unique-names (sap size)
588 `(multiple-value-bind (,sap ,var ,size)
590 (values nil (int-sap 0))
591 #-win32 (string-list-to-c-strvec ,str-list)
592 #+win32 (encode-windows-environment ,str-list))
597 (deallocate-system-memory ,sap ,size)))))))
599 (sb-alien:define-alien-routine spawn
601 #+win32 sb-win32::handle
602 (program sb-alien:c-string)
603 (argv (* sb-alien:c-string))
605 (stdout sb-alien:int)
606 (stderr sb-alien:int)
607 (search sb-alien:int)
608 (envp (* sb-alien:c-string))
609 (pty-name sb-alien:c-string)
611 (pwd sb-alien:c-string))
613 ;;; FIXME: There shouldn't be two semiredundant versions of the
614 ;;; documentation. Since this is a public extension function, the
615 ;;; documentation should be in the doc string. So all information from
616 ;;; this comment should be merged into the doc string, and then this
617 ;;; comment can go away.
619 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
620 ;;; Strange stuff happens to keep the Unix state of the world
623 ;;; The child process needs to get its input from somewhere, and send
624 ;;; its output (both standard and error) to somewhere. We have to do
625 ;;; different things depending on where these somewheres really are.
627 ;;; For input, there are five options:
628 ;;; -- T: Just leave fd 0 alone. Pretty simple.
629 ;;; -- "file": Read from the file. We need to open the file and
630 ;;; pull the descriptor out of the stream. The parent should close
631 ;;; this stream after the child is up and running to free any
632 ;;; storage used in the parent.
633 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
634 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
635 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
636 ;;; writeable descriptor, and pass the readable descriptor to
637 ;;; the child. The parent must close the readable descriptor for
638 ;;; EOF to be passed up correctly.
639 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
640 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
641 ;;; everything across.
643 ;;; For output, there are five options:
644 ;;; -- T: Leave descriptor 1 alone.
645 ;;; -- "file": dump output to the file.
646 ;;; -- NIL: dump output to /dev/null.
647 ;;; -- :STREAM: return a stream that can be read from.
648 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
649 ;;; Otherwise, copy stuff from output to stream.
651 ;;; For error, there are all the same options as output plus:
652 ;;; -- :OUTPUT: redirect to the same place as output.
654 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
655 ;;; the fork worked, and NIL if it did not.
656 (defun run-program (program args
661 (unix-environment-sbcl-from-cmucl env))
667 if-input-does-not-exist
669 (if-output-exists :error)
671 (if-error-exists :error)
673 (external-format :default)
674 (directory nil directory-p))
678 ;; The Texinfoizer is sensitive to whitespace, so mind the
679 ;; placement of the #-win32 pseudosplicings.
680 "RUN-PROGRAM creates a new process specified by the PROGRAM
681 argument. ARGS are the standard arguments that can be passed to a
682 program. For no arguments, use NIL (which means that just the
683 name of the program is passed as arg 0).
685 The program arguments and the environment are encoded using the
686 default external format for streams.
688 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
689 Users Manual for details about the PROCESS structure."#-win32"
691 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
693 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
694 programs, but unlike the original CMU CL implementation, copies
695 the Unix environment by default.
697 - Running Unix programs from a setuid process, or in any other
698 situation where the Unix environment is under the control of someone
699 else, is a mother lode of security problems. If you are contemplating
700 doing this, read about it first. (The Perl community has a lot of good
701 documentation about this and other security issues in script-like
704 The &KEY arguments have the following meanings:
706 a list of STRINGs describing the new Unix environment
707 (as in \"man environ\"). The default is to copy the environment of
710 an alternative lossy representation of the new Unix environment,
711 for compatibility with CMU CL
713 Look for PROGRAM in each of the directories in the child's $PATH
714 environment variable. Otherwise an absolute pathname is required.
716 If non-NIL (default), wait until the created process finishes. If
717 NIL, continue running Lisp until the program finishes."#-win32"
719 Either T, NIL, or a stream. Unless NIL, the subprocess is established
720 under a PTY. If :pty is a stream, all output to this pty is sent to
721 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
722 connected to pty that can read output and write input.""
724 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
725 input for the current process is inherited. If NIL, "
726 #-win32"/dev/null"#+win32"nul""
727 is used. If a pathname, the file so specified is used. If a stream,
728 all the input is read from that stream and sent to the subprocess. If
729 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
730 its output to the process. Defaults to NIL.
731 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
733 :ERROR to generate an error
734 :CREATE to create an empty file
735 NIL (the default) to return NIL from RUN-PROGRAM
737 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
738 output for the current process is inherited. If NIL, "
739 #-win32"/dev/null"#+win32"nul""
740 is used. If a pathname, the file so specified is used. If a stream,
741 all the output from the process is written to this stream. If
742 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
743 be read to get the output. Defaults to NIL.
744 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
746 :ERROR (the default) to generate an error
747 :SUPERSEDE to supersede the file with output from the program
748 :APPEND to append output from the program to the file
749 NIL to return NIL from RUN-PROGRAM, without doing anything
750 :ERROR and :IF-ERROR-EXISTS
751 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
752 specified as :OUTPUT in which case all error output is routed to the
753 same place as normal output.
755 This is a function the system calls whenever the status of the
756 process changes. The function takes the process as an argument.
758 The external-format to use for :INPUT, :OUTPUT, and :ERROR :STREAMs.
760 Specifies the directory in which the program should be run.
761 NIL (the default) means the directory is unchanged.")
762 (when (and env-p environment-p)
763 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
764 ;; Prepend the program to the argument list.
765 (push (namestring program) args)
766 (labels (;; It's friendly to allow the caller to pass any string
767 ;; designator, but internally we'd like SIMPLE-STRINGs.
769 ;; Huh? We let users pass in symbols and characters for
770 ;; the arguments, but call NAMESTRING on the program
772 (simplify-args (args)
773 (loop for arg in args
774 as escaped-arg = (escape-arg arg)
775 collect (coerce escaped-arg 'simple-string)))
778 ;; Apparently any spaces or double quotes in the arguments
779 ;; need to be escaped on win32.
780 #+win32 (if (position-if
781 (lambda (c) (find c '(#\" #\Space))) arg)
782 (write-to-string arg)
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 (simple-args (simplify-args args))
794 (progname (native-namestring program))
798 ;; Note: despite the WITH-* names, these macros don't
799 ;; expand into UNWIND-PROTECT forms. They're just
800 ;; syntactic sugar to make the rest of the routine slightly
802 (macrolet ((with-no-with
804 (&whole form with-something parameters &body body))
805 (declare (ignore with-something parameters))
807 (keyword `(progn ,@body))
809 (t `(let ,no (declare (ignorable ,@no)) ,@body))))
810 (with-fd-and-stream-for (((fd stream) which &rest args)
812 `(multiple-value-bind (,fd ,stream)
815 `(get-descriptor-for ,@args))
817 `(if (eq ,(first args) :output)
818 ;; kludge: we expand into
819 ;; hard-coded symbols here.
820 (values stdout output-stream)
821 (get-descriptor-for ,@args))))
823 (return-from run-program))
825 (with-open-pty (((pty-name pty-stream) (pty cookie))
827 `(multiple-value-bind (,pty-name ,pty-stream)
828 (open-pty ,pty ,cookie :external-format external-format)
830 (with-args-vec ((vec args) &body body)
831 `(with-c-strvec (,vec ,args)
833 (with-environment-vec ((vec) &body body)
836 :null (not (or environment environment-p)))
838 (with-fd-and-stream-for ((stdin input-stream) :input
841 :if-does-not-exist if-input-does-not-exist
842 :external-format external-format
844 (with-fd-and-stream-for ((stdout output-stream) :output
847 :if-exists if-output-exists
848 :external-format external-format)
849 (with-fd-and-stream-for ((stderr error-stream) :error
852 :if-exists if-error-exists
853 :external-format external-format)
854 (with-no-with (#+win32 (pty-name pty-stream))
855 (with-open-pty ((pty-name pty-stream) (pty cookie))
856 ;; Make sure we are not notified about the child
857 ;; death before we have installed the PROCESS
858 ;; structure in *ACTIVE-PROCESSES*.
860 (with-active-processes-lock ()
861 (with-no-with (#+win32 (args-vec))
862 (with-args-vec (args-vec simple-args)
863 (with-environment-vec (environment-vec)
865 (and directory-p (native-namestring directory))))
868 (sb-win32::mswin-spawn
870 (with-output-to-string (argv)
871 (dolist (arg simple-args)
872 (write-string arg argv)
873 (write-char #\Space argv)))
875 search environment-vec wait pwd-string)
878 (spawn progname args-vec
881 environment-vec pty-name
884 (unless (minusp child)
889 :output output-stream
891 :status-hook status-hook
893 #-win32 (list :pty pty-stream
897 (list :%status :exited
899 (list :%status :running
901 (push proc *active-processes*))))))
902 ;; Report the error outside the lock.
905 (error "Couldn't fork child process: ~A"
908 (error "Couldn't execute ~S: ~A"
909 progname (strerror)))
911 (error "Couldn't change directory to ~S: ~A"
912 directory (strerror)))))))))))
913 (dolist (fd *close-in-parent*)
914 (sb-unix:unix-close fd))
916 (dolist (fd *close-on-error*)
917 (sb-unix:unix-close fd))
919 (dolist (handler *handlers-installed*)
920 (remove-fd-handler handler)))
922 (when (and wait proc)
925 (dolist (handler *handlers-installed*)
926 (remove-fd-handler handler)))))
929 ;;; Install a handler for any input that shows up on the file
930 ;;; descriptor. The handler reads the data and writes it to the
932 (defun copy-descriptor-to-stream (descriptor stream cookie external-format)
935 (buf (make-array 256 :element-type '(unsigned-byte 8)))
937 (et (stream-element-type stream))
940 ((member et '(character base-char))
942 (let* ((decode-end read-end)
943 (string (handler-case
946 :external-format external-format)
947 (end-of-input-in-character (e)
949 (octet-decoding-error-start e))
952 :external-format external-format)))))
953 (unless (zerop (length string))
954 (write-string string stream)
955 (when (/= decode-end (length buf))
956 (replace buf buf :start2 decode-end :end2 read-end))
957 (decf read-end decode-end)))))
958 ((member et '(:default (unsigned-byte 8)) :test #'equal)
960 (write-sequence buf stream :end read-end)
964 (error "Don't know how to copy to stream of element-type ~S"
971 (declare (ignore fd))
976 (result readable/errno)
977 (sb-unix:unix-select (1+ descriptor)
981 (if (eql sb-unix:eintr readable/errno)
983 (error "~@<Couldn't select on sub-process: ~
985 (strerror readable/errno))))
988 (multiple-value-bind (count errno)
989 (with-pinned-objects (buf)
990 (sb-unix:unix-read descriptor
991 (sap+ (vector-sap buf) read-end)
992 (- (length buf) read-end)))
994 ((and #-win32 (or (and (null count)
995 (eql errno sb-unix:eio))
997 #+win32 (<= count 0))
998 (remove-fd-handler handler)
1001 (sb-unix:unix-close descriptor)
1002 (unless (zerop read-end)
1003 ;; Should this be an END-OF-FILE?
1004 (error "~@<non-empty buffer when EOF reached ~
1005 while reading from child: ~S~:>" buf))
1008 (remove-fd-handler handler)
1012 "~@<couldn't read input from sub-process: ~
1016 (incf read-end count)
1017 (funcall copy-fun))))))))
1019 (push handler *handlers-installed*)))
1021 ;;; FIXME: something very like this is done in SB-POSIX to treat
1022 ;;; streams as file descriptor designators; maybe we can combine these
1023 ;;; two? Additionally, as we have a couple of user-defined streams
1024 ;;; libraries, maybe we should have a generic function for doing this,
1025 ;;; so user-defined streams can play nicely with RUN-PROGRAM (and
1026 ;;; maybe also with SB-POSIX)?
1027 (defun get-stream-fd-and-external-format (stream direction)
1030 (values (fd-stream-fd stream) nil (stream-external-format stream)))
1032 (get-stream-fd-and-external-format
1033 (symbol-value (synonym-stream-symbol stream)) direction))
1037 (get-stream-fd-and-external-format
1038 (two-way-stream-input-stream stream) direction))
1040 (get-stream-fd-and-external-format
1041 (two-way-stream-output-stream stream) direction))))))
1043 (defun get-temporary-directory ()
1044 #-win32 (or (sb-ext:posix-getenv "TMPDIR")
1046 #+win32 (or (sb-ext:posix-getenv "TEMP")
1050 ;;; Find a file descriptor to use for object given the direction.
1051 ;;; Returns the descriptor. If object is :STREAM, returns the created
1052 ;;; stream as the second value.
1053 (defun get-descriptor-for (object
1056 &key direction (external-format :default) wait
1058 (declare (ignore wait)) ;This is explained below.
1059 ;; Our use of a temporary file dates back to very old CMUCLs, and
1060 ;; was probably only ever intended for use with STRING-STREAMs,
1061 ;; which are ordinarily smallish. However, as we've got
1062 ;; user-defined stream classes, we can end up trying to copy
1063 ;; arbitrarily much data into the temp file, and so are liable to
1064 ;; run afoul of disk quotas or to choke on small /tmp file systems.
1065 (flet ((make-temp-fd ()
1066 (multiple-value-bind (fd name/errno)
1067 (sb-unix:sb-mkstemp (format nil "~a/.run-program-XXXXXX"
1068 (get-temporary-directory))
1071 (error "could not open a temporary file: ~A"
1072 (strerror name/errno)))
1073 ;; Can't unlink an open file on Windows
1075 (unless (sb-unix:unix-unlink name/errno)
1076 (sb-unix:unix-close fd)
1077 (error "failed to unlink ~A" name/errno))
1079 (let ((dev-null #.(coerce #-win32 "/dev/null" #+win32 "nul" 'base-string)))
1080 (cond ((eq object t)
1081 ;; No new descriptor is needed.
1083 ((or (eq object nil)
1084 (and (typep object 'broadcast-stream)
1085 (not (broadcast-stream-streams object))))
1087 (multiple-value-bind
1089 (sb-unix:unix-open dev-null
1091 (:input sb-unix:o_rdonly)
1092 (:output sb-unix:o_wronly)
1096 (error "~@<couldn't open ~S: ~2I~_~A~:>"
1097 dev-null (strerror errno)))
1099 (setf (sb-win32::inheritable-handle-p fd) t)
1100 (push fd *close-in-parent*)
1102 ((eq object :stream)
1103 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
1105 (error "couldn't create pipe: ~A" (strerror write-fd)))
1107 (setf (sb-win32::inheritable-handle-p read-fd)
1108 (eq direction :input)
1109 (sb-win32::inheritable-handle-p write-fd)
1110 (eq direction :output))
1113 (push read-fd *close-in-parent*)
1114 (push write-fd *close-on-error*)
1115 (let ((stream (make-fd-stream write-fd :output t
1116 :element-type :default
1119 (values read-fd stream)))
1121 (push read-fd *close-on-error*)
1122 (push write-fd *close-in-parent*)
1123 (let ((stream (make-fd-stream read-fd :input t
1124 :element-type :default
1127 (values write-fd stream)))
1129 (sb-unix:unix-close read-fd)
1130 (sb-unix:unix-close write-fd)
1131 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
1133 ((or (pathnamep object) (stringp object))
1134 ;; GET-DESCRIPTOR-FOR uses &allow-other-keys, so rather
1135 ;; than munge the &rest list for OPEN, just disable keyword
1136 ;; validation there.
1137 (with-open-stream (file (apply #'open object :allow-other-keys t
1140 (multiple-value-bind
1142 (sb-unix:unix-dup (fd-stream-fd file))
1144 (push fd *close-in-parent*)
1147 (error "couldn't duplicate file descriptor: ~A"
1148 (strerror errno))))))))
1153 ;; If we can get an fd for the stream, let the child
1154 ;; process use the fd for its descriptor. Otherwise,
1155 ;; we copy data from the stream into a temp file, and
1156 ;; give the temp file's descriptor to the
1158 (multiple-value-bind (fd stream format)
1159 (get-stream-fd-and-external-format object :input)
1160 (declare (ignore format))
1162 (return (values fd stream))))
1163 ;; FIXME: if we can't get the file descriptor, since
1164 ;; the stream might be interactive or otherwise
1165 ;; block-y, we can't know whether we can copy the
1166 ;; stream's data to a temp file, so if RUN-PROGRAM was
1167 ;; called with :WAIT NIL, we should probably error.
1168 ;; However, STRING-STREAMs aren't fd-streams, but
1169 ;; they're not prone to blocking; any user-defined
1170 ;; streams that "read" from some in-memory data will
1171 ;; probably be similar to STRING-STREAMs. So maybe we
1172 ;; should add a STREAM-INTERACTIVE-P generic function
1173 ;; for problems like this? Anyway, the machinery is
1174 ;; here, if you feel like filling in the details.
1176 (when (and (null wait) #<some undetermined criterion>)
1177 (error "~@<don't know how to get an fd for ~A, and so ~
1178 can't ensure that copying its data to the ~
1179 child process won't hang~:>" object))
1181 (let ((fd (make-temp-fd))
1182 (et (stream-element-type object)))
1183 (cond ((member et '(character base-char))
1185 (multiple-value-bind
1187 (read-line object nil nil)
1190 (let ((vector (string-to-octets
1192 :external-format external-format)))
1194 fd vector 0 (length vector)))
1198 fd #.(string #\Newline) 0 1)))))
1199 ((member et '(:default (unsigned-byte 8))
1201 (loop with buf = (make-array 256 :element-type '(unsigned-byte 8))
1202 for p = (read-sequence buf object)
1204 do (sb-unix:unix-write fd buf 0 p)))
1206 (error "Don't know how to copy from stream of element-type ~S"
1208 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1209 (push fd *close-in-parent*)
1210 (return (values fd nil)))))
1213 ;; Similar to the :input trick above, except we
1214 ;; arrange to copy data from the stream. This is
1215 ;; slightly saner than the input case, since we don't
1216 ;; buffer to a file, but I think we may still lose if
1217 ;; there's unflushed data in the stream buffer and we
1218 ;; give the file descriptor to the child.
1219 (multiple-value-bind (fd stream format)
1220 (get-stream-fd-and-external-format object :output)
1221 (declare (ignore format))
1223 (return (values fd stream))))
1224 (multiple-value-bind (read-fd write-fd)
1227 (error "couldn't create pipe: ~S" (strerror write-fd)))
1228 (copy-descriptor-to-stream read-fd object cookie
1230 (push read-fd *close-on-error*)
1231 (push write-fd *close-in-parent*)
1232 (return (values write-fd nil)))))
1234 (error "invalid option to RUN-PROGRAM: ~S" object))))))))