1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
\r
2 ;;;; from inside SBCL
\r
4 ;;;; This software is part of the SBCL system. See the README file for
\r
5 ;;;; more information.
\r
7 ;;;; This software is derived from the CMU CL system, which was
\r
8 ;;;; written at Carnegie Mellon University and released into the
\r
9 ;;;; public domain. The software is in the public domain and is
\r
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
\r
11 ;;;; files for more information.
\r
13 (in-package "SB-IMPL") ;(SB-IMPL, not SB!IMPL, since we're built in warm load.)
\r
15 ;;;; hacking the Unix environment
\r
17 ;;;; In the original CMU CL code that LOAD-FOREIGN is derived from, the
\r
18 ;;;; Unix environment (as in "man environ") was represented as an
\r
19 ;;;; alist from keywords to strings, so that e.g. the Unix environment
\r
20 ;;;; "SHELL=/bin/bash" "HOME=/root" "PAGER=less"
\r
21 ;;;; was represented as
\r
22 ;;;; ((:SHELL . "/bin/bash") (:HOME . "/root") (:PAGER "less"))
\r
23 ;;;; This had a few problems in principle: the mapping into
\r
24 ;;;; keyword symbols smashed the case of environment
\r
25 ;;;; variables, and the whole mapping depended on the presence of
\r
26 ;;;; #\= characters in the environment strings. In practice these
\r
27 ;;;; problems weren't hugely important, since conventionally environment
\r
28 ;;;; variables are uppercase strings followed by #\= followed by
\r
29 ;;;; arbitrary data. However, since it's so manifestly not The Right
\r
30 ;;;; Thing to make code which breaks unnecessarily on input which
\r
31 ;;;; doesn't follow what is, after all, only a tradition, we've switched
\r
32 ;;;; formats in SBCL, so that the fundamental environment list
\r
33 ;;;; is just a list of strings, with a one-to-one-correspondence
\r
34 ;;;; to the C-level representation. I.e., in the example above,
\r
35 ;;;; the SBCL representation is
\r
36 ;;;; '("SHELL=/bin/bash" "HOME=/root" "PAGER=less")
\r
37 ;;;; CMU CL's implementation is currently supported to help with porting.
\r
39 ;;;; It's not obvious that this code belongs here (instead of e.g. in
\r
40 ;;;; unix.lisp), since it has only a weak logical connection with
\r
41 ;;;; RUN-PROGRAM. However, physically it's convenient to put it here.
\r
42 ;;;; It's not needed at cold init, so we *can* put it in this
\r
43 ;;;; warm-loaded file. And by putting it in this warm-loaded file, we
\r
44 ;;;; make it easy for it to get to the C-level 'environ' variable.
\r
45 ;;;; which (at least in sbcl-0.6.10 on Red Hat Linux 6.2) is not
\r
46 ;;;; visible at GENESIS time.
\r
50 (define-alien-routine wrapped-environ (* c-string))
\r
51 (defun posix-environ ()
\r
52 "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
\r
53 (c-strings->string-list (wrapped-environ))))
\r
55 ;#+win32 (sb-alien:define-alien-routine msvcrt-environ (* c-string))
\r
57 ;;; Convert as best we can from an SBCL representation of a Unix
\r
58 ;;; environment to a CMU CL representation.
\r
60 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
\r
62 ;;; smashing case of "Bletch=fub" in conversion to CMU-CL-style
\r
63 ;;; environment alist
\r
65 ;;; no #\= in "Noggin", eliding it in CMU-CL-style environment alist
\r
66 ;;; ((:BLETCH . "fub") (:YES . "No!"))
\r
67 (defun unix-environment-cmucl-from-sbcl (sbcl)
\r
70 (declare (type simple-base-string string))
\r
71 (let ((=-pos (position #\= string :test #'equal)))
\r
74 (let* ((key-as-string (subseq string 0 =-pos))
\r
75 (key-as-upcase-string (string-upcase key-as-string))
\r
76 (key (keywordicate key-as-upcase-string))
\r
77 (val (subseq string (1+ =-pos))))
\r
78 (unless (string= key-as-string key-as-upcase-string)
\r
79 (warn "smashing case of ~S in conversion to CMU-CL-style ~
\r
83 (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
\r
87 ;;; Convert from a CMU CL representation of a Unix environment to a
\r
88 ;;; SBCL representation.
\r
89 (defun unix-environment-sbcl-from-cmucl (cmucl)
\r
92 (destructuring-bind (key . val) cons
\r
93 (declare (type keyword key) (type simple-base-string val))
\r
94 (concatenate 'simple-base-string (symbol-name key) "=" val)))
\r
97 ;;;; Import wait3(2) from Unix.
\r
100 (define-alien-routine ("wait3" c-wait3) sb-alien:int
\r
101 (status sb-alien:int :out)
\r
102 (options sb-alien:int)
\r
103 (rusage sb-alien:int))
\r
106 (defun wait3 (&optional do-not-hang check-for-stopped)
\r
108 "Return any available status information on child process. "
\r
109 (multiple-value-bind (pid status)
\r
110 (c-wait3 (logior (if do-not-hang
\r
113 (if check-for-stopped
\r
117 (cond ((or (minusp pid)
\r
120 ((eql (ldb (byte 8 0) status)
\r
124 (ldb (byte 8 8) status)))
\r
125 ((zerop (ldb (byte 7 0) status))
\r
128 (ldb (byte 8 8) status)))
\r
130 (let ((signal (ldb (byte 7 0) status)))
\r
132 (if (position signal
\r
141 (not (zerop (ldb (byte 1 7) status)))))))))
\r
143 ;;;; process control stuff
\r
144 (defvar *active-processes* nil
\r
146 "List of process structures for all active processes.")
\r
149 (defvar *active-processes-lock*
\r
150 (sb-thread:make-mutex :name "Lock for active processes."))
\r
152 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
\r
153 ;;; mutex is needed. More importantly the sigchld signal handler also
\r
154 ;;; accesses it, that's why we need without-interrupts.
\r
155 (defmacro with-active-processes-lock (() &body body)
\r
157 `(without-interrupts
\r
158 (sb-thread:with-mutex (*active-processes-lock*)
\r
163 (defstruct (process (:copier nil))
\r
164 pid ; PID of child process
\r
165 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
\r
166 exit-code ; either exit code or signal
\r
167 core-dumped ; T if a core image was dumped
\r
168 #-win32 pty ; stream to child's pty, or NIL
\r
169 input ; stream to child's input, or NIL
\r
170 output ; stream from child's output, or NIL
\r
171 error ; stream from child's error output, or NIL
\r
172 status-hook ; closure to call when PROC changes status
\r
173 plist ; a place for clients to stash things
\r
174 cookie) ; list of the number of pipes from the subproc
\r
176 (defmethod print-object ((process process) stream)
\r
177 (print-unreadable-object (process stream :type t)
\r
178 (let ((status (process-status process)))
\r
179 (if (eq :exited status)
\r
180 (format stream "~S ~S" status (process-exit-code process))
\r
181 (format stream "~S ~S" (process-pid process) status)))
\r
185 (setf (documentation 'process-p 'function)
\r
186 "T if OBJECT is a PROCESS, NIL otherwise.")
\r
189 (setf (documentation 'process-pid 'function) "The pid of the child process.")
\r
192 (define-alien-routine ("GetExitCodeProcess@8" get-exit-code-process)
\r
194 (handle unsigned) (exit-code unsigned :out))
\r
196 (defun process-status (process)
\r
198 "Return the current status of PROCESS. The result is one of :RUNNING,
\r
199 :STOPPED, :EXITED, or :SIGNALED."
\r
200 (get-processes-status-changes)
\r
201 (process-%status process))
\r
204 (setf (documentation 'process-exit-code 'function)
\r
205 "The exit code or the signal of a stopped process.")
\r
208 (setf (documentation 'process-core-dumped 'function)
\r
209 "T if a core image was dumped by the process.")
\r
212 (setf (documentation 'process-pty 'function)
\r
213 "The pty stream of the process or NIL.")
\r
216 (setf (documentation 'process-input 'function)
\r
217 "The input stream of the process or NIL.")
\r
220 (setf (documentation 'process-output 'function)
\r
221 "The output stream of the process or NIL.")
\r
224 (setf (documentation 'process-error 'function)
\r
225 "The error stream of the process or NIL.")
\r
228 (setf (documentation 'process-status-hook 'function)
\r
229 "A function that is called when PROCESS changes its status.
\r
230 The function is called with PROCESS as its only argument.")
\r
233 (setf (documentation 'process-plist 'function)
\r
234 "A place for clients to stash things.")
\r
236 (defun process-wait (process &optional check-for-stopped)
\r
238 "Wait for PROCESS to quit running for some reason. When
\r
239 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
\r
242 (case (process-status process)
\r
245 (when check-for-stopped
\r
248 (when (zerop (car (process-cookie process)))
\r
250 (sb-sys:serve-all-events 1))
\r
254 ;;; Find the current foreground process group id.
\r
255 (defun find-current-foreground-process (proc)
\r
256 (with-alien ((result sb-alien:int))
\r
257 (multiple-value-bind
\r
259 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
\r
261 (alien-sap (sb-alien:addr result)))
\r
263 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
\r
265 (process-pid proc))
\r
268 (defun process-kill (process signal &optional (whom :pid))
\r
270 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
\r
271 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
\r
272 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
\r
273 currently in the foreground."
\r
274 (let ((pid (ecase whom
\r
275 ((:pid :process-group)
\r
276 (process-pid process))
\r
277 (:pty-process-group
\r
279 (find-current-foreground-process process)))))
\r
280 (multiple-value-bind
\r
284 (:pty-process-group
\r
285 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty process))
\r
286 sb-unix:TIOCSIGSEND
\r
289 ((:process-group #-hpux :pty-process-group)
\r
290 (sb-unix:unix-killpg pid signal))
\r
292 (sb-unix:unix-kill pid signal)))
\r
294 (values nil errno))
\r
295 ((and (eql pid (process-pid process))
\r
296 (= signal sb-unix:sigcont))
\r
297 (setf (process-%status process) :running)
\r
298 (setf (process-exit-code process) nil)
\r
299 (when (process-status-hook process)
\r
300 (funcall (process-status-hook process) process))
\r
305 (defun process-alive-p (process)
\r
307 "Return T if PROCESS is still alive, NIL otherwise."
\r
308 (let ((status (process-status process)))
\r
309 (if (or (eq status :running)
\r
310 (eq status :stopped))
\r
314 (defun process-close (process)
\r
316 "Close all streams connected to PROCESS and stop maintaining the
\r
318 (macrolet ((frob (stream abort)
\r
319 `(when ,stream (close ,stream :abort ,abort))))
\r
321 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process,
\r
322 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
\r
323 (frob (process-output process) nil)
\r
324 (frob (process-error process) nil))
\r
325 ;; FIXME: Given that the status-slot is no longer updated,
\r
326 ;; maybe it should be set to :CLOSED, or similar?
\r
327 (with-active-processes-lock ()
\r
328 (setf *active-processes* (delete process *active-processes*)))
\r
331 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
\r
333 (defun sigchld-handler (ignore1 ignore2 ignore3)
\r
334 (declare (ignore ignore1 ignore2 ignore3))
\r
335 (get-processes-status-changes))
\r
337 (defun get-processes-status-changes ()
\r
340 (multiple-value-bind (pid what code core)
\r
344 (let ((proc (with-active-processes-lock ()
\r
345 (find pid *active-processes* :key #'process-pid))))
\r
347 (setf (process-%status proc) what)
\r
348 (setf (process-exit-code proc) code)
\r
349 (setf (process-core-dumped proc) core)
\r
350 (when (process-status-hook proc)
\r
351 (funcall (process-status-hook proc) proc))
\r
352 (when (position what #(:exited :signaled))
\r
353 (with-active-processes-lock ()
\r
354 (setf *active-processes*
\r
355 (delete proc *active-processes*))))))))
\r
358 (with-active-processes-lock ()
\r
359 (setf *active-processes*
\r
360 (delete-if (lambda (proc)
\r
361 (multiple-value-bind (ok code)
\r
362 (get-exit-code-process (process-pid proc))
\r
363 (when (and (plusp ok) (/= code 259))
\r
364 (setf (process-%status proc) :exited
\r
365 (process-exit-code proc) code)
\r
366 (when (process-status-hook proc)
\r
367 (push proc exited))
\r
369 *active-processes*)))
\r
370 ;; Can't call the hooks before all the processes have been deal
\r
371 ;; with, as calling a hook may cause re-entry to
\r
372 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using wait3,
\r
373 ;; but in the Windows implementation is would be deeply bad.
\r
374 (dolist (proc exited)
\r
375 (let ((hook (process-status-hook proc)))
\r
377 (funcall hook proc))))))
\r
379 ;;;; RUN-PROGRAM and close friends
\r
381 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
\r
382 (defvar *close-on-error* nil)
\r
384 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
\r
385 (defvar *close-in-parent* nil)
\r
387 ;;; list of handlers installed by RUN-PROGRAM
\r
389 (defvar *handlers-installed* nil)
\r
391 ;;; Find an unused pty. Return three values: the file descriptor for
\r
392 ;;; the master side of the pty, the file descriptor for the slave side
\r
393 ;;; of the pty, and the name of the tty device for the slave side.
\r
395 (defun find-a-pty ()
\r
396 (dolist (char '(#\p #\q))
\r
397 (dotimes (digit 16)
\r
398 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit) 'base-string))
\r
399 (master-fd (sb-unix:unix-open master-name
\r
403 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit) 'base-string))
\r
404 (slave-fd (sb-unix:unix-open slave-name
\r
408 (return-from find-a-pty
\r
412 (sb-unix:unix-close master-fd))))))
\r
413 (error "could not find a pty"))
\r
416 (defun open-pty (pty cookie)
\r
418 (multiple-value-bind
\r
419 (master slave name)
\r
421 (push master *close-on-error*)
\r
422 (push slave *close-in-parent*)
\r
423 (when (streamp pty)
\r
424 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
\r
426 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
\r
427 (push new-fd *close-on-error*)
\r
428 (copy-descriptor-to-stream new-fd pty cookie)))
\r
430 (sb-sys:make-fd-stream master :input t :output t
\r
431 :element-type :default
\r
432 :dual-channel-p t)))))
\r
434 (defmacro round-bytes-to-words (n)
\r
435 `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
\r
437 (defun string-list-to-c-strvec (string-list)
\r
438 ;; Make a pass over STRING-LIST to calculate the amount of memory
\r
439 ;; needed to hold the strvec.
\r
440 (let ((string-bytes 0)
\r
441 ;; We need an extra for the null, and an extra 'cause exect
\r
442 ;; clobbers argv[-1].
\r
443 (vec-bytes (* #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)
\r
444 (+ (length string-list) 2))))
\r
445 (declare (fixnum string-bytes vec-bytes))
\r
446 (dolist (s string-list)
\r
447 (enforce-type s simple-string)
\r
448 (incf string-bytes (round-bytes-to-words (1+ (length s)))))
\r
449 ;; Now allocate the memory and fill it in.
\r
450 (let* ((total-bytes (+ string-bytes vec-bytes))
\r
451 (vec-sap (sb-sys:allocate-system-memory total-bytes))
\r
452 (string-sap (sap+ vec-sap vec-bytes))
\r
453 (i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits)))
\r
454 (declare (type (and unsigned-byte fixnum) total-bytes i)
\r
455 (type sb-sys:system-area-pointer vec-sap string-sap))
\r
456 (dolist (s string-list)
\r
457 (declare (simple-string s))
\r
458 (let ((n (length s)))
\r
459 ;; Blast the string into place.
\r
460 (sb-kernel:copy-ub8-to-system-area (the simple-base-string
\r
462 (coerce s 'simple-base-string))
\r
466 ;; Blast the pointer to the string into place.
\r
467 (setf (sap-ref-sap vec-sap i) string-sap)
\r
468 (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
\r
469 (incf i #.(/ sb-vm::n-machine-word-bits sb-vm::n-byte-bits))))
\r
470 ;; Blast in the last null pointer.
\r
471 (setf (sap-ref-sap vec-sap i) (int-sap 0))
\r
472 (values vec-sap (sap+ vec-sap #.(/ sb-vm::n-machine-word-bits
\r
473 sb-vm::n-byte-bits))
\r
476 (defmacro with-c-strvec ((var str-list) &body body)
\r
477 (with-unique-names (sap size)
\r
478 `(multiple-value-bind
\r
480 (string-list-to-c-strvec ,str-list)
\r
484 (sb-sys:deallocate-system-memory ,sap ,size)))))
\r
487 (sb-alien:define-alien-routine spawn sb-alien:int
\r
488 (program sb-alien:c-string)
\r
489 (argv (* sb-alien:c-string))
\r
490 (envp (* sb-alien:c-string))
\r
491 (pty-name sb-alien:c-string)
\r
492 (stdin sb-alien:int)
\r
493 (stdout sb-alien:int)
\r
494 (stderr sb-alien:int))
\r
497 (sb-alien:define-alien-routine spawn sb-win32::handle
\r
498 (program sb-alien:c-string)
\r
499 (argv (* sb-alien:c-string))
\r
500 (stdin sb-alien:int)
\r
501 (stdout sb-alien:int)
\r
502 (stderr sb-alien:int)
\r
503 (wait sb-alien:int))
\r
505 ;;; Is UNIX-FILENAME the name of a file that we can execute?
\r
506 (defun unix-filename-is-executable-p (unix-filename)
\r
507 (let ((filename (coerce unix-filename 'base-string)))
\r
508 (values (and (eq (sb-unix:unix-file-kind filename) :file)
\r
510 (sb-unix:unix-access filename sb-unix:x_ok)))))
\r
512 (defun find-executable-in-search-path (pathname &optional
\r
513 (search-path (posix-getenv "PATH")))
\r
515 "Find the first executable file matching PATHNAME in any of the
\r
516 colon-separated list of pathnames SEARCH-PATH"
\r
517 (let ((program #-win32 pathname
\r
518 #+win32 (merge-pathnames pathname (make-pathname :type "exe"))))
\r
519 (loop for end = (position #-win32 #\: #+win32 #\; search-path
\r
520 :start (if end (1+ end) 0))
\r
521 and start = 0 then (and end (1+ end))
\r
523 ;; <Krystof> the truename of a file naming a directory is the
\r
524 ;; directory, at least until pfdietz comes along and says why
\r
525 ;; that's noncompliant -- CSR, c. 2003-08-10
\r
526 for truename = (probe-file (subseq search-path start end))
\r
527 for fullpath = (when truename
\r
528 (unix-namestring (merge-pathnames program truename)))
\r
529 when (and fullpath (unix-filename-is-executable-p fullpath))
\r
532 ;;; FIXME: There shouldn't be two semiredundant versions of the
\r
533 ;;; documentation. Since this is a public extension function, the
\r
534 ;;; documentation should be in the doc string. So all information from
\r
535 ;;; this comment should be merged into the doc string, and then this
\r
536 ;;; comment can go away.
\r
538 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
\r
539 ;;; Strange stuff happens to keep the Unix state of the world
\r
542 ;;; The child process needs to get its input from somewhere, and send
\r
543 ;;; its output (both standard and error) to somewhere. We have to do
\r
544 ;;; different things depending on where these somewheres really are.
\r
546 ;;; For input, there are five options:
\r
547 ;;; -- T: Just leave fd 0 alone. Pretty simple.
\r
548 ;;; -- "file": Read from the file. We need to open the file and
\r
549 ;;; pull the descriptor out of the stream. The parent should close
\r
550 ;;; this stream after the child is up and running to free any
\r
551 ;;; storage used in the parent.
\r
552 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
\r
553 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
\r
554 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
\r
555 ;;; writeable descriptor, and pass the readable descriptor to
\r
556 ;;; the child. The parent must close the readable descriptor for
\r
557 ;;; EOF to be passed up correctly.
\r
558 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
\r
559 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
\r
560 ;;; everything across.
\r
562 ;;; For output, there are five options:
\r
563 ;;; -- T: Leave descriptor 1 alone.
\r
564 ;;; -- "file": dump output to the file.
\r
565 ;;; -- NIL: dump output to /dev/null.
\r
566 ;;; -- :STREAM: return a stream that can be read from.
\r
567 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
\r
568 ;;; Otherwise, copy stuff from output to stream.
\r
570 ;;; For error, there are all the same options as output plus:
\r
571 ;;; -- :OUTPUT: redirect to the same place as output.
\r
573 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
\r
574 ;;; the fork worked, and NIL if it did not.
\r
577 (defun run-program (program args
\r
580 (environment (if env-p
\r
581 (unix-environment-sbcl-from-cmucl env)
\r
588 if-input-does-not-exist
\r
590 (if-output-exists :error)
\r
592 (if-error-exists :error)
\r
595 "RUN-PROGRAM creates a new Unix process running the Unix program
\r
596 found in the file specified by the PROGRAM argument. ARGS are the
\r
597 standard arguments that can be passed to a Unix program. For no
\r
598 arguments, use NIL (which means that just the name of the program is
\r
601 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
\r
602 Users Manual for details about the PROCESS structure.
\r
604 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
\r
606 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
\r
607 programs, but unlike the original CMU CL implementation, copies
\r
608 the Unix environment by default.
\r
610 - Running Unix programs from a setuid process, or in any other
\r
611 situation where the Unix environment is under the control of someone
\r
612 else, is a mother lode of security problems. If you are contemplating
\r
613 doing this, read about it first. (The Perl community has a lot of good
\r
614 documentation about this and other security issues in script-like
\r
617 The &KEY arguments have the following meanings:
\r
620 a list of SIMPLE-BASE-STRINGs describing the new Unix environment
\r
621 (as in \"man environ\"). The default is to copy the environment of
\r
622 the current process.
\r
624 an alternative lossy representation of the new Unix environment,
\r
625 for compatibility with CMU CL
\r
627 Look for PROGRAM in each of the directories along the $PATH
\r
628 environment variable. Otherwise an absolute pathname is required.
\r
629 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
\r
631 If non-NIL (default), wait until the created process finishes. If
\r
632 NIL, continue running Lisp until the program finishes.
\r
634 Either T, NIL, or a stream. Unless NIL, the subprocess is established
\r
635 under a PTY. If :pty is a stream, all output to this pty is sent to
\r
636 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
\r
637 connected to pty that can read output and write input.
\r
639 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
\r
640 input for the current process is inherited. If NIL, /dev/null
\r
641 is used. If a pathname, the file so specified is used. If a stream,
\r
642 all the input is read from that stream and send to the subprocess. If
\r
643 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
\r
644 its output to the process. Defaults to NIL.
\r
645 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
\r
647 :ERROR to generate an error
\r
648 :CREATE to create an empty file
\r
649 NIL (the default) to return NIL from RUN-PROGRAM
\r
651 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
\r
652 output for the current process is inherited. If NIL, /dev/null
\r
653 is used. If a pathname, the file so specified is used. If a stream,
\r
654 all the output from the process is written to this stream. If
\r
655 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
\r
656 be read to get the output. Defaults to NIL.
\r
657 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
\r
659 :ERROR (the default) to generate an error
\r
660 :SUPERSEDE to supersede the file with output from the program
\r
661 :APPEND to append output from the program to the file
\r
662 NIL to return NIL from RUN-PROGRAM, without doing anything
\r
663 :ERROR and :IF-ERROR-EXISTS
\r
664 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
\r
665 specified as :OUTPUT in which case all error output is routed to the
\r
666 same place as normal output.
\r
668 This is a function the system calls whenever the status of the
\r
669 process changes. The function takes the process as an argument."
\r
670 (when (and env-p environment-p)
\r
671 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
\r
672 ;; Make sure that the interrupt handler is installed.
\r
673 (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
\r
674 ;; Prepend the program to the argument list.
\r
675 (push (namestring program) args)
\r
676 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
\r
677 ;; communicate cleanup info.
\r
680 *handlers-installed*
\r
681 ;; Establish PROC at this level so that we can return it.
\r
683 ;; It's friendly to allow the caller to pass any string
\r
684 ;; designator, but internally we'd like SIMPLE-STRINGs.
\r
685 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
\r
689 (find-executable-in-search-path program)
\r
690 (unix-namestring program)))
\r
693 (error "no such program: ~S" program))
\r
694 (unless (unix-filename-is-executable-p pfile)
\r
695 (error "not executable: ~S" program))
\r
696 (multiple-value-bind (stdin input-stream)
\r
697 (get-descriptor-for input cookie
\r
699 :if-does-not-exist if-input-does-not-exist)
\r
700 (multiple-value-bind (stdout output-stream)
\r
701 (get-descriptor-for output cookie
\r
703 :if-exists if-output-exists)
\r
704 (multiple-value-bind (stderr error-stream)
\r
705 (if (eq error :output)
\r
706 (values stdout output-stream)
\r
707 (get-descriptor-for error cookie
\r
709 :if-exists if-error-exists))
\r
710 (multiple-value-bind (pty-name pty-stream)
\r
711 (open-pty pty cookie)
\r
712 ;; Make sure we are not notified about the child
\r
713 ;; death before we have installed the PROCESS
\r
714 ;; structure in *ACTIVE-PROCESSES*.
\r
715 (with-active-processes-lock ()
\r
716 (with-c-strvec (args-vec simple-args)
\r
717 (with-c-strvec (environment-vec environment)
\r
720 (spawn pfile args-vec environment-vec pty-name
\r
721 stdin stdout stderr))))
\r
722 (when (< child-pid 0)
\r
723 (error "couldn't fork child process: ~A"
\r
725 (setf proc (make-process :pid child-pid
\r
728 :input input-stream
\r
729 :output output-stream
\r
730 :error error-stream
\r
731 :status-hook status-hook
\r
733 (push proc *active-processes*))))))))))
\r
734 (dolist (fd *close-in-parent*)
\r
735 (sb-unix:unix-close fd))
\r
737 (dolist (fd *close-on-error*)
\r
738 (sb-unix:unix-close fd))
\r
739 (dolist (handler *handlers-installed*)
\r
740 (sb-sys:remove-fd-handler handler))))
\r
741 (when (and wait proc)
\r
742 (process-wait proc))
\r
746 (defun run-program (program args
\r
751 if-input-does-not-exist
\r
753 (if-output-exists :error)
\r
755 (if-error-exists :error)
\r
757 "RUN-PROGRAM creates a new process specified by the PROGRAM
\r
758 argument. ARGS are the standard arguments that can be passed to a
\r
759 program. For no arguments, use NIL (which means that just the name of
\r
760 the program is passed as arg 0).
\r
762 RUN-PROGRAM will return a PROCESS structure. See the CMU
\r
763 Common Lisp Users Manual for details about the PROCESS structure.
\r
765 The &KEY arguments have the following meanings:
\r
767 Look for PROGRAM in each of the directories along the $PATH
\r
768 environment variable. Otherwise an absolute pathname is required.
\r
769 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
\r
771 If non-NIL (default), wait until the created process finishes. If
\r
772 NIL, continue running Lisp until the program finishes.
\r
774 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
\r
775 input for the current process is inherited. If NIL, nul
\r
776 is used. If a pathname, the file so specified is used. If a stream,
\r
777 all the input is read from that stream and send to the subprocess. If
\r
778 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
\r
779 its output to the process. Defaults to NIL.
\r
780 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
\r
782 :ERROR to generate an error
\r
783 :CREATE to create an empty file
\r
784 NIL (the default) to return NIL from RUN-PROGRAM
\r
786 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
\r
787 output for the current process is inherited. If NIL, nul
\r
788 is used. If a pathname, the file so specified is used. If a stream,
\r
789 all the output from the process is written to this stream. If
\r
790 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
\r
791 be read to get the output. Defaults to NIL.
\r
792 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
\r
794 :ERROR (the default) to generate an error
\r
795 :SUPERSEDE to supersede the file with output from the program
\r
796 :APPEND to append output from the program to the file
\r
797 NIL to return NIL from RUN-PROGRAM, without doing anything
\r
798 :ERROR and :IF-ERROR-EXISTS
\r
799 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
\r
800 specified as :OUTPUT in which case all error output is routed to the
\r
801 same place as normal output.
\r
803 This is a function the system calls whenever the status of the
\r
804 process changes. The function takes the process as an argument."
\r
805 ;; Prepend the program to the argument list.
\r
806 (push (namestring program) args)
\r
807 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
\r
808 ;; communicate cleanup info.
\r
811 ;; Establish PROC at this level so that we can return it.
\r
813 ;; It's friendly to allow the caller to pass any string
\r
814 ;; designator, but internally we'd like SIMPLE-STRINGs.
\r
815 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
\r
819 (find-executable-in-search-path program)
\r
820 (unix-namestring program)))
\r
823 (error "No such program: ~S" program))
\r
824 (unless (unix-filename-is-executable-p pfile)
\r
825 (error "Not an executable: ~S" program))
\r
826 (multiple-value-bind (stdin input-stream)
\r
827 (get-descriptor-for input cookie
\r
829 :if-does-not-exist if-input-does-not-exist)
\r
830 (multiple-value-bind (stdout output-stream)
\r
831 (get-descriptor-for output cookie
\r
833 :if-exists if-output-exists)
\r
834 (multiple-value-bind (stderr error-stream)
\r
835 (if (eq error :output)
\r
836 (values stdout output-stream)
\r
837 (get-descriptor-for error cookie
\r
839 :if-exists if-error-exists))
\r
840 (with-c-strvec (args-vec simple-args)
\r
841 (let ((handle (without-gcing
\r
842 (spawn pfile args-vec
\r
843 stdin stdout stderr
\r
846 (error "Couldn't spawn program: ~A" (strerror)))
\r
849 (make-process :pid handle
\r
851 :input input-stream
\r
852 :output output-stream
\r
853 :error error-stream
\r
854 :status-hook status-hook
\r
857 (make-process :pid handle
\r
859 :input input-stream
\r
860 :output output-stream
\r
861 :error error-stream
\r
862 :status-hook status-hook
\r
864 (push proc *active-processes*)))))))
\r
865 (dolist (fd *close-in-parent*)
\r
866 (sb-unix:unix-close fd)))
\r
868 (dolist (fd *close-on-error*)
\r
869 (sb-unix:unix-close fd)))
\r
873 ;;; Install a handler for any input that shows up on the file
\r
874 ;;; descriptor. The handler reads the data and writes it to the
\r
876 (defun copy-descriptor-to-stream (descriptor stream cookie)
\r
877 (incf (car cookie))
\r
878 (let ((string (make-string 256 :element-type 'base-char))
\r
881 (sb-sys:add-fd-handler
\r
883 :input (lambda (fd)
\r
884 (declare (ignore fd))
\r
888 (multiple-value-bind
\r
889 (result readable/errno)
\r
890 (sb-unix:unix-select (1+ descriptor)
\r
893 (cond ((null result)
\r
894 (error "~@<couldn't select on sub-process: ~
\r
896 (strerror readable/errno)))
\r
899 (sb-alien:with-alien ((buf (sb-alien:array
\r
902 (multiple-value-bind
\r
904 (sb-unix:unix-read descriptor
\r
907 (cond (#-win32(or (and (null count)
\r
908 (eql errno sb-unix:eio))
\r
910 #+win32(<= count 0)
\r
911 (sb-sys:remove-fd-handler handler)
\r
913 (decf (car cookie))
\r
914 (sb-unix:unix-close descriptor)
\r
917 (sb-sys:remove-fd-handler handler)
\r
919 (decf (car cookie))
\r
921 "~@<couldn't read input from sub-process: ~
\r
925 (sb-kernel:copy-ub8-from-system-area
\r
929 (write-string string stream
\r
930 :end count)))))))))))
\r
932 (defun get-stream-fd (stream direction)
\r
935 (values (sb-sys:fd-stream-fd stream) nil))
\r
937 (get-stream-fd (symbol-value (synonym-stream-symbol stream)) direction))
\r
941 (get-stream-fd (two-way-stream-input-stream stream) direction))
\r
943 (get-stream-fd (two-way-stream-output-stream stream) direction))))))
\r
945 ;;; Find a file descriptor to use for object given the direction.
\r
946 ;;; Returns the descriptor. If object is :STREAM, returns the created
\r
947 ;;; stream as the second value.
\r
948 (defun get-descriptor-for (object
\r
953 (cond ((eq object t)
\r
954 ;; No new descriptor is needed.
\r
958 (multiple-value-bind
\r
960 (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
\r
961 #+win32 #.(coerce "nul" 'base-string)
\r
963 (:input sb-unix:o_rdonly)
\r
964 (:output sb-unix:o_wronly)
\r
965 (t sb-unix:o_rdwr))
\r
968 (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
\r
969 #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"
\r
971 (push fd *close-in-parent*)
\r
973 ((eq object :stream)
\r
974 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
\r
976 (error "couldn't create pipe: ~A" (strerror write-fd)))
\r
979 (push read-fd *close-in-parent*)
\r
980 (push write-fd *close-on-error*)
\r
981 (let ((stream (sb-sys:make-fd-stream write-fd :output t
\r
982 :element-type :default)))
\r
983 (values read-fd stream)))
\r
985 (push read-fd *close-on-error*)
\r
986 (push write-fd *close-in-parent*)
\r
987 (let ((stream (sb-sys:make-fd-stream read-fd :input t
\r
988 :element-type :default)))
\r
989 (values write-fd stream)))
\r
991 (sb-unix:unix-close read-fd)
\r
992 (sb-unix:unix-close write-fd)
\r
993 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
\r
995 ((or (pathnamep object) (stringp object))
\r
996 (with-open-stream (file (apply #'open object keys))
\r
997 (multiple-value-bind
\r
999 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
\r
1001 (push fd *close-in-parent*)
\r
1004 (error "couldn't duplicate file descriptor: ~A"
\r
1005 (strerror errno)))))))
\r
1009 (or (get-stream-fd object :input)
\r
1010 ;; FIXME: We could use a better way of setting up
\r
1011 ;; temporary files
\r
1014 (error "could not open a temporary file in /tmp"))
\r
1015 (let* ((name (coerce (format nil "/tmp/.run-program-~D" count)
\r
1017 (fd (sb-unix:unix-open name
\r
1018 (logior sb-unix:o_rdwr
\r
1022 (sb-unix:unix-unlink name)
\r
1024 (let ((newline (string #\Newline)))
\r
1026 (multiple-value-bind
\r
1028 (read-line object nil nil)
\r
1031 (sb-unix:unix-write
\r
1033 ;; FIXME: this really should be
\r
1034 ;; (STRING-TO-OCTETS :EXTERNAL-FORMAT ...).
\r
1035 ;; RUN-PROGRAM should take an
\r
1036 ;; external-format argument, which should
\r
1037 ;; be passed down to here. Something
\r
1038 ;; similar should happen on :OUTPUT, too.
\r
1039 (map '(vector (unsigned-byte 8)) #'char-code line)
\r
1043 (sb-unix:unix-write fd newline 0 1)))))
\r
1044 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
\r
1045 (push fd *close-in-parent*)
\r
1046 (return (values fd nil)))))))
\r
1048 (or (get-stream-fd object :output)
\r
1049 (multiple-value-bind (read-fd write-fd)
\r
1050 (sb-unix:unix-pipe)
\r
1052 (error "couldn't create pipe: ~S" (strerror write-fd)))
\r
1053 (copy-descriptor-to-stream read-fd object cookie)
\r
1054 (push read-fd *close-on-error*)
\r
1055 (push write-fd *close-in-parent*)
\r
1056 (values write-fd nil))))))
\r
1058 (error "invalid option to RUN-PROGRAM: ~S" object))))
\r