1.0.6.36: ALLOW-WITH-INTERRUPTS and interrupt safe WITH-MUTEX &co
[sbcl/simd.git] / src / code / run-program.lisp
blob5c4f9fc229ce023d87850aa1c5033fffc7849cb7
1 ;;;; RUN-PROGRAM and friends, a facility for running Unix programs
2 ;;;; from inside SBCL
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
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
16 ;;;;
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.
38 ;;;;
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.
48 #-win32
49 (progn
50 (define-alien-routine wrapped-environ (* c-string))
51 (defun posix-environ ()
52 "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
53 (c-strings->string-list (wrapped-environ))))
55 ;#+win32 (sb-alien:define-alien-routine msvcrt-environ (* c-string))
57 ;;; Convert as best we can from an SBCL representation of a Unix
58 ;;; environment to a CMU CL representation.
59 ;;;
60 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
61 ;;; WARNING:
62 ;;; smashing case of "Bletch=fub" in conversion to CMU-CL-style
63 ;;; environment alist
64 ;;; WARNING:
65 ;;; no #\= in "Noggin", eliding it in CMU-CL-style environment alist
66 ;;; ((:BLETCH . "fub") (:YES . "No!"))
67 (defun unix-environment-cmucl-from-sbcl (sbcl)
68 (mapcan
69 (lambda (string)
70 (declare (type simple-base-string string))
71 (let ((=-pos (position #\= string :test #'equal)))
72 (if =-pos
73 (list
74 (let* ((key-as-string (subseq string 0 =-pos))
75 (key-as-upcase-string (string-upcase key-as-string))
76 (key (keywordicate key-as-upcase-string))
77 (val (subseq string (1+ =-pos))))
78 (unless (string= key-as-string key-as-upcase-string)
79 (warn "smashing case of ~S in conversion to CMU-CL-style ~
80 environment alist"
81 string))
82 (cons key val)))
83 (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
84 string))))
85 sbcl))
87 ;;; Convert from a CMU CL representation of a Unix environment to a
88 ;;; SBCL representation.
89 (defun unix-environment-sbcl-from-cmucl (cmucl)
90 (mapcar
91 (lambda (cons)
92 (destructuring-bind (key . val) cons
93 (declare (type keyword key) (type simple-base-string val))
94 (concatenate 'simple-base-string (symbol-name key) "=" val)))
95 cmucl))
97 ;;;; Import wait3(2) from Unix.
99 #-win32
100 (define-alien-routine ("wait3" c-wait3) sb-alien:int
101 (status sb-alien:int :out)
102 (options sb-alien:int)
103 (rusage sb-alien:int))
105 #-win32
106 (defun wait3 (&optional do-not-hang check-for-stopped)
107 #+sb-doc
108 "Return any available status information on child process. "
109 (multiple-value-bind (pid status)
110 (c-wait3 (logior (if do-not-hang
111 sb-unix:wnohang
113 (if check-for-stopped
114 sb-unix:wuntraced
117 (cond ((or (minusp pid)
118 (zerop pid))
119 nil)
120 ((eql (ldb (byte 8 0) status)
121 sb-unix:wstopped)
122 (values pid
123 :stopped
124 (ldb (byte 8 8) status)))
125 ((zerop (ldb (byte 7 0) status))
126 (values pid
127 :exited
128 (ldb (byte 8 8) status)))
130 (let ((signal (ldb (byte 7 0) status)))
131 (values pid
132 (if (position signal
133 #.(vector
134 sb-unix:sigstop
135 sb-unix:sigtstp
136 sb-unix:sigttin
137 sb-unix:sigttou))
138 :stopped
139 :signaled)
140 signal
141 (not (zerop (ldb (byte 1 7) status)))))))))
143 ;;;; process control stuff
144 (defvar *active-processes* nil
145 #+sb-doc
146 "List of process structures for all active processes.")
148 #-win32
149 (defvar *active-processes-lock*
150 (sb-thread:make-mutex :name "Lock for active processes."))
152 ;;; *ACTIVE-PROCESSES* can be accessed from multiple threads so a
153 ;;; mutex is needed. More importantly the sigchld signal handler also
154 ;;; accesses it, that's why we need without-interrupts.
155 (defmacro with-active-processes-lock (() &body body)
156 #-win32
157 `(sb-thread::call-with-system-mutex (lambda () ,@body) *active-processes-lock*)
158 #+win32
159 `(progn ,@body))
161 (defstruct (process (:copier nil))
162 pid ; PID of child process
163 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
164 exit-code ; either exit code or signal
165 core-dumped ; T if a core image was dumped
166 #-win32 pty ; stream to child's pty, or NIL
167 input ; stream to child's input, or NIL
168 output ; stream from child's output, or NIL
169 error ; stream from child's error output, or NIL
170 status-hook ; closure to call when PROC changes status
171 plist ; a place for clients to stash things
172 cookie) ; list of the number of pipes from the subproc
174 (defmethod print-object ((process process) stream)
175 (print-unreadable-object (process stream :type t)
176 (let ((status (process-status process)))
177 (if (eq :exited status)
178 (format stream "~S ~S" status (process-exit-code process))
179 (format stream "~S ~S" (process-pid process) status)))
180 process))
182 #+sb-doc
183 (setf (documentation 'process-p 'function)
184 "T if OBJECT is a PROCESS, NIL otherwise.")
186 #+sb-doc
187 (setf (documentation 'process-pid 'function) "The pid of the child process.")
189 #+win32
190 (define-alien-routine ("GetExitCodeProcess@8" get-exit-code-process)
192 (handle unsigned) (exit-code unsigned :out))
194 (defun process-status (process)
195 #+sb-doc
196 "Return the current status of PROCESS. The result is one of :RUNNING,
197 :STOPPED, :EXITED, or :SIGNALED."
198 (get-processes-status-changes)
199 (process-%status process))
201 #+sb-doc
202 (setf (documentation 'process-exit-code 'function)
203 "The exit code or the signal of a stopped process.")
205 #+sb-doc
206 (setf (documentation 'process-core-dumped 'function)
207 "T if a core image was dumped by the process.")
209 #+sb-doc
210 (setf (documentation 'process-pty 'function)
211 "The pty stream of the process or NIL.")
213 #+sb-doc
214 (setf (documentation 'process-input 'function)
215 "The input stream of the process or NIL.")
217 #+sb-doc
218 (setf (documentation 'process-output 'function)
219 "The output stream of the process or NIL.")
221 #+sb-doc
222 (setf (documentation 'process-error 'function)
223 "The error stream of the process or NIL.")
225 #+sb-doc
226 (setf (documentation 'process-status-hook 'function)
227 "A function that is called when PROCESS changes its status.
228 The function is called with PROCESS as its only argument.")
230 #+sb-doc
231 (setf (documentation 'process-plist 'function)
232 "A place for clients to stash things.")
234 (defun process-wait (process &optional check-for-stopped)
235 #+sb-doc
236 "Wait for PROCESS to quit running for some reason. When
237 CHECK-FOR-STOPPED is T, also returns when PROCESS is stopped. Returns
238 PROCESS."
239 (loop
240 (case (process-status process)
241 (:running)
242 (:stopped
243 (when check-for-stopped
244 (return)))
246 (when (zerop (car (process-cookie process)))
247 (return))))
248 (sb-sys:serve-all-events 1))
249 process)
251 #-(or hpux win32)
252 ;;; Find the current foreground process group id.
253 (defun find-current-foreground-process (proc)
254 (with-alien ((result sb-alien:int))
255 (multiple-value-bind
256 (wonp error)
257 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
258 sb-unix:TIOCGPGRP
259 (alien-sap (sb-alien:addr result)))
260 (unless wonp
261 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
262 result))
263 (process-pid proc))
265 #-win32
266 (defun process-kill (process signal &optional (whom :pid))
267 #+sb-doc
268 "Hand SIGNAL to PROCESS. If WHOM is :PID, use the kill Unix system call. If
269 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
270 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
271 currently in the foreground."
272 (let ((pid (ecase whom
273 ((:pid :process-group)
274 (process-pid process))
275 (:pty-process-group
276 #-hpux
277 (find-current-foreground-process process)))))
278 (multiple-value-bind
279 (okay errno)
280 (case whom
281 #+hpux
282 (:pty-process-group
283 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty process))
284 sb-unix:TIOCSIGSEND
285 (sb-sys:int-sap
286 signal)))
287 ((:process-group #-hpux :pty-process-group)
288 (sb-unix:unix-killpg pid signal))
290 (sb-unix:unix-kill pid signal)))
291 (cond ((not okay)
292 (values nil errno))
293 ((and (eql pid (process-pid process))
294 (= signal sb-unix:sigcont))
295 (setf (process-%status process) :running)
296 (setf (process-exit-code process) nil)
297 (when (process-status-hook process)
298 (funcall (process-status-hook process) process))
301 t)))))
303 (defun process-alive-p (process)
304 #+sb-doc
305 "Return T if PROCESS is still alive, NIL otherwise."
306 (let ((status (process-status process)))
307 (if (or (eq status :running)
308 (eq status :stopped))
310 nil)))
312 (defun process-close (process)
313 #+sb-doc
314 "Close all streams connected to PROCESS and stop maintaining the
315 status slot."
316 (macrolet ((frob (stream abort)
317 `(when ,stream (close ,stream :abort ,abort))))
318 #-win32
319 (frob (process-pty process) t) ; Don't FLUSH-OUTPUT to dead process,
320 (frob (process-input process) t) ; .. 'cause it will generate SIGPIPE.
321 (frob (process-output process) nil)
322 (frob (process-error process) nil))
323 ;; FIXME: Given that the status-slot is no longer updated,
324 ;; maybe it should be set to :CLOSED, or similar?
325 (with-active-processes-lock ()
326 (setf *active-processes* (delete process *active-processes*)))
327 process)
329 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
330 #-win32
331 (defun sigchld-handler (ignore1 ignore2 ignore3)
332 (declare (ignore ignore1 ignore2 ignore3))
333 (get-processes-status-changes))
335 (defun get-processes-status-changes ()
336 #-win32
337 (loop
338 (multiple-value-bind (pid what code core)
339 (wait3 t t)
340 (unless pid
341 (return))
342 (let ((proc (with-active-processes-lock ()
343 (find pid *active-processes* :key #'process-pid))))
344 (when proc
345 (setf (process-%status proc) what)
346 (setf (process-exit-code proc) code)
347 (setf (process-core-dumped proc) core)
348 (when (process-status-hook proc)
349 (funcall (process-status-hook proc) proc))
350 (when (position what #(:exited :signaled))
351 (with-active-processes-lock ()
352 (setf *active-processes*
353 (delete proc *active-processes*))))))))
354 #+win32
355 (let (exited)
356 (with-active-processes-lock ()
357 (setf *active-processes*
358 (delete-if (lambda (proc)
359 (multiple-value-bind (ok code)
360 (get-exit-code-process (process-pid proc))
361 (when (and (plusp ok) (/= code 259))
362 (setf (process-%status proc) :exited
363 (process-exit-code proc) code)
364 (when (process-status-hook proc)
365 (push proc exited))
366 t)))
367 *active-processes*)))
368 ;; Can't call the hooks before all the processes have been deal
369 ;; with, as calling a hook may cause re-entry to
370 ;; GET-PROCESS-STATUS-CHANGES. That may be OK when using wait3,
371 ;; but in the Windows implementation is would be deeply bad.
372 (dolist (proc exited)
373 (let ((hook (process-status-hook proc)))
374 (when hook
375 (funcall hook proc))))))
377 ;;;; RUN-PROGRAM and close friends
379 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
380 (defvar *close-on-error* nil)
382 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
383 (defvar *close-in-parent* nil)
385 ;;; list of handlers installed by RUN-PROGRAM
386 #-win32
387 (defvar *handlers-installed* nil)
389 ;;; Find an unused pty. Return three values: the file descriptor for
390 ;;; the master side of the pty, the file descriptor for the slave side
391 ;;; of the pty, and the name of the tty device for the slave side.
392 #-win32
393 (progn
394 (define-alien-routine ptsname c-string (fd int))
395 (define-alien-routine grantpt boolean (fd int))
396 (define-alien-routine unlockpt boolean (fd int))
398 (defun find-a-pty ()
399 ;; First try to use the Unix98 pty api.
400 (let* ((master-name (coerce (format nil "/dev/ptmx") 'base-string))
401 (master-fd (sb-unix:unix-open master-name
402 sb-unix:o_rdwr
403 #o666)))
404 (when master-fd
405 (grantpt master-fd)
406 (unlockpt master-fd)
407 (let* ((slave-name (ptsname master-fd))
408 (slave-fd (sb-unix:unix-open slave-name
409 sb-unix:o_rdwr
410 #o666)))
411 (when slave-fd
412 (return-from find-a-pty
413 (values master-fd
414 slave-fd
415 slave-name)))
416 (sb-unix:unix-close master-fd))
417 (error "could not find a pty")))
418 ;; No dice, try using the old-school method.
419 (dolist (char '(#\p #\q))
420 (dotimes (digit 16)
421 (let* ((master-name (coerce (format nil "/dev/pty~C~X" char digit)
422 'base-string))
423 (master-fd (sb-unix:unix-open master-name
424 sb-unix:o_rdwr
425 #o666)))
426 (when master-fd
427 (let* ((slave-name (coerce (format nil "/dev/tty~C~X" char digit)
428 'base-string))
429 (slave-fd (sb-unix:unix-open slave-name
430 sb-unix:o_rdwr
431 #o666)))
432 (when slave-fd
433 (return-from find-a-pty
434 (values master-fd
435 slave-fd
436 slave-name)))
437 (sb-unix:unix-close master-fd))))))
438 (error "could not find a pty")))
440 #-win32
441 (defun open-pty (pty cookie)
442 (when pty
443 (multiple-value-bind
444 (master slave name)
445 (find-a-pty)
446 (push master *close-on-error*)
447 (push slave *close-in-parent*)
448 (when (streamp pty)
449 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
450 (unless new-fd
451 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
452 (push new-fd *close-on-error*)
453 (copy-descriptor-to-stream new-fd pty cookie)))
454 (values name
455 (sb-sys:make-fd-stream master :input t :output t
456 :element-type :default
457 :dual-channel-p t)))))
459 (defmacro round-bytes-to-words (n)
460 (let ((bytes-per-word (/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
461 `(logandc2 (the fixnum (+ (the fixnum ,n)
462 (1- ,bytes-per-word))) (1- ,bytes-per-word))))
464 (defun string-list-to-c-strvec (string-list)
465 ;; Make a pass over STRING-LIST to calculate the amount of memory
466 ;; needed to hold the strvec.
467 (let ((string-bytes 0)
468 ;; We need an extra for the null, and an extra 'cause exect
469 ;; clobbers argv[-1].
470 (vec-bytes (* #.(/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)
471 (+ (length string-list) 2))))
472 (declare (fixnum string-bytes vec-bytes))
473 (dolist (s string-list)
474 (enforce-type s simple-string)
475 (incf string-bytes (round-bytes-to-words (1+ (length s)))))
476 ;; Now allocate the memory and fill it in.
477 (let* ((total-bytes (+ string-bytes vec-bytes))
478 (vec-sap (sb-sys:allocate-system-memory total-bytes))
479 (string-sap (sap+ vec-sap vec-bytes))
480 (i #.(/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits)))
481 (declare (type (and unsigned-byte fixnum) total-bytes i)
482 (type sb-sys:system-area-pointer vec-sap string-sap))
483 (dolist (s string-list)
484 (declare (simple-string s))
485 (let ((n (length s)))
486 ;; Blast the string into place.
487 (sb-kernel:copy-ub8-to-system-area (the simple-base-string
488 ;; FIXME
489 (coerce s 'simple-base-string))
491 string-sap 0
492 (1+ n))
493 ;; Blast the pointer to the string into place.
494 (setf (sap-ref-sap vec-sap i) string-sap)
495 (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
496 (incf i #.(/ sb-vm:n-machine-word-bits sb-vm:n-byte-bits))))
497 ;; Blast in the last null pointer.
498 (setf (sap-ref-sap vec-sap i) (int-sap 0))
499 (values vec-sap (sap+ vec-sap #.(/ sb-vm:n-machine-word-bits
500 sb-vm:n-byte-bits))
501 total-bytes))))
503 (defmacro with-c-strvec ((var str-list) &body body)
504 (with-unique-names (sap size)
505 `(multiple-value-bind
506 (,sap ,var ,size)
507 (string-list-to-c-strvec ,str-list)
508 (unwind-protect
509 (progn
510 ,@body)
511 (sb-sys:deallocate-system-memory ,sap ,size)))))
513 #-win32
514 (sb-alien:define-alien-routine spawn sb-alien:int
515 (program sb-alien:c-string)
516 (argv (* sb-alien:c-string))
517 (envp (* sb-alien:c-string))
518 (pty-name sb-alien:c-string)
519 (stdin sb-alien:int)
520 (stdout sb-alien:int)
521 (stderr sb-alien:int))
523 #+win32
524 (sb-alien:define-alien-routine spawn sb-win32::handle
525 (program sb-alien:c-string)
526 (argv (* sb-alien:c-string))
527 (stdin sb-alien:int)
528 (stdout sb-alien:int)
529 (stderr sb-alien:int)
530 (wait sb-alien:int))
532 ;;; Is UNIX-FILENAME the name of a file that we can execute?
533 (defun unix-filename-is-executable-p (unix-filename)
534 (let ((filename (coerce unix-filename 'string)))
535 (values (and (eq (sb-unix:unix-file-kind filename) :file)
536 #-win32
537 (sb-unix:unix-access filename sb-unix:x_ok)))))
539 (defun find-executable-in-search-path (pathname &optional
540 (search-path (posix-getenv "PATH")))
541 #+sb-doc
542 "Find the first executable file matching PATHNAME in any of the
543 colon-separated list of pathnames SEARCH-PATH"
544 (let ((program #-win32 pathname
545 #+win32 (merge-pathnames pathname (make-pathname :type "exe"))))
546 (loop for end = (position #-win32 #\: #+win32 #\; search-path
547 :start (if end (1+ end) 0))
548 and start = 0 then (and end (1+ end))
549 while start
550 ;; <Krystof> the truename of a file naming a directory is the
551 ;; directory, at least until pfdietz comes along and says why
552 ;; that's noncompliant -- CSR, c. 2003-08-10
553 for truename = (probe-file (subseq search-path start end))
554 for fullpath = (when truename
555 (unix-namestring (merge-pathnames program truename)))
556 when (and fullpath (unix-filename-is-executable-p fullpath))
557 return fullpath)))
559 ;;; FIXME: There shouldn't be two semiredundant versions of the
560 ;;; documentation. Since this is a public extension function, the
561 ;;; documentation should be in the doc string. So all information from
562 ;;; this comment should be merged into the doc string, and then this
563 ;;; comment can go away.
565 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
566 ;;; Strange stuff happens to keep the Unix state of the world
567 ;;; coherent.
569 ;;; The child process needs to get its input from somewhere, and send
570 ;;; its output (both standard and error) to somewhere. We have to do
571 ;;; different things depending on where these somewheres really are.
573 ;;; For input, there are five options:
574 ;;; -- T: Just leave fd 0 alone. Pretty simple.
575 ;;; -- "file": Read from the file. We need to open the file and
576 ;;; pull the descriptor out of the stream. The parent should close
577 ;;; this stream after the child is up and running to free any
578 ;;; storage used in the parent.
579 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
580 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
581 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
582 ;;; writeable descriptor, and pass the readable descriptor to
583 ;;; the child. The parent must close the readable descriptor for
584 ;;; EOF to be passed up correctly.
585 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
586 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
587 ;;; everything across.
589 ;;; For output, there are five options:
590 ;;; -- T: Leave descriptor 1 alone.
591 ;;; -- "file": dump output to the file.
592 ;;; -- NIL: dump output to /dev/null.
593 ;;; -- :STREAM: return a stream that can be read from.
594 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
595 ;;; Otherwise, copy stuff from output to stream.
597 ;;; For error, there are all the same options as output plus:
598 ;;; -- :OUTPUT: redirect to the same place as output.
600 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
601 ;;; the fork worked, and NIL if it did not.
603 #-win32
604 (defun run-program (program args
605 &key
606 (env nil env-p)
607 (environment (if env-p
608 (unix-environment-sbcl-from-cmucl env)
609 (posix-environ))
610 environment-p)
611 (wait t)
612 search
614 input
615 if-input-does-not-exist
616 output
617 (if-output-exists :error)
618 (error :output)
619 (if-error-exists :error)
620 status-hook)
621 #+sb-doc
622 "RUN-PROGRAM creates a new Unix process running the Unix program
623 found in the file specified by the PROGRAM argument. ARGS are the
624 standard arguments that can be passed to a Unix program. For no
625 arguments, use NIL (which means that just the name of the program is
626 passed as arg 0).
628 RUN-PROGRAM will return a PROCESS structure. See the CMU Common Lisp
629 Users Manual for details about the PROCESS structure.
631 Notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
633 - The SBCL implementation of RUN-PROGRAM, like Perl and many other
634 programs, but unlike the original CMU CL implementation, copies
635 the Unix environment by default.
637 - Running Unix programs from a setuid process, or in any other
638 situation where the Unix environment is under the control of someone
639 else, is a mother lode of security problems. If you are contemplating
640 doing this, read about it first. (The Perl community has a lot of good
641 documentation about this and other security issues in script-like
642 programs.)
644 The &KEY arguments have the following meanings:
646 :ENVIRONMENT
647 a list of SIMPLE-BASE-STRINGs describing the new Unix environment
648 (as in \"man environ\"). The default is to copy the environment of
649 the current process.
650 :ENV
651 an alternative lossy representation of the new Unix environment,
652 for compatibility with CMU CL
653 :SEARCH
654 Look for PROGRAM in each of the directories along the $PATH
655 environment variable. Otherwise an absolute pathname is required.
656 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
657 :WAIT
658 If non-NIL (default), wait until the created process finishes. If
659 NIL, continue running Lisp until the program finishes.
660 :PTY
661 Either T, NIL, or a stream. Unless NIL, the subprocess is established
662 under a PTY. If :pty is a stream, all output to this pty is sent to
663 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
664 connected to pty that can read output and write input.
665 :INPUT
666 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
667 input for the current process is inherited. If NIL, /dev/null
668 is used. If a pathname, the file so specified is used. If a stream,
669 all the input is read from that stream and send to the subprocess. If
670 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
671 its output to the process. Defaults to NIL.
672 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
673 can be one of:
674 :ERROR to generate an error
675 :CREATE to create an empty file
676 NIL (the default) to return NIL from RUN-PROGRAM
677 :OUTPUT
678 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
679 output for the current process is inherited. If NIL, /dev/null
680 is used. If a pathname, the file so specified is used. If a stream,
681 all the output from the process is written to this stream. If
682 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
683 be read to get the output. Defaults to NIL.
684 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
685 can be one of:
686 :ERROR (the default) to generate an error
687 :SUPERSEDE to supersede the file with output from the program
688 :APPEND to append output from the program to the file
689 NIL to return NIL from RUN-PROGRAM, without doing anything
690 :ERROR and :IF-ERROR-EXISTS
691 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
692 specified as :OUTPUT in which case all error output is routed to the
693 same place as normal output.
694 :STATUS-HOOK
695 This is a function the system calls whenever the status of the
696 process changes. The function takes the process as an argument."
697 (when (and env-p environment-p)
698 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
699 ;; Make sure that the interrupt handler is installed.
700 (sb-sys:enable-interrupt sb-unix:sigchld #'sigchld-handler)
701 ;; Prepend the program to the argument list.
702 (push (namestring program) args)
703 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
704 ;; communicate cleanup info.
705 *close-on-error*
706 *close-in-parent*
707 *handlers-installed*
708 ;; Establish PROC at this level so that we can return it.
709 proc
710 ;; It's friendly to allow the caller to pass any string
711 ;; designator, but internally we'd like SIMPLE-STRINGs.
712 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
713 (unwind-protect
714 (let ((pfile
715 (if search
716 (find-executable-in-search-path program)
717 (unix-namestring program)))
718 (cookie (list 0)))
719 (unless pfile
720 (error "no such program: ~S" program))
721 (unless (unix-filename-is-executable-p pfile)
722 (error "not executable: ~S" program))
723 (multiple-value-bind (stdin input-stream)
724 (get-descriptor-for input cookie
725 :direction :input
726 :if-does-not-exist if-input-does-not-exist)
727 (multiple-value-bind (stdout output-stream)
728 (get-descriptor-for output cookie
729 :direction :output
730 :if-exists if-output-exists)
731 (multiple-value-bind (stderr error-stream)
732 (if (eq error :output)
733 (values stdout output-stream)
734 (get-descriptor-for error cookie
735 :direction :output
736 :if-exists if-error-exists))
737 (multiple-value-bind (pty-name pty-stream)
738 (open-pty pty cookie)
739 ;; Make sure we are not notified about the child
740 ;; death before we have installed the PROCESS
741 ;; structure in *ACTIVE-PROCESSES*.
742 (with-active-processes-lock ()
743 (with-c-strvec (args-vec simple-args)
744 (with-c-strvec (environment-vec environment)
745 (let ((child-pid
746 (without-gcing
747 (spawn pfile args-vec environment-vec pty-name
748 stdin stdout stderr))))
749 (when (< child-pid 0)
750 (error "couldn't fork child process: ~A"
751 (strerror)))
752 (setf proc (make-process :pid child-pid
753 :%status :running
754 :pty pty-stream
755 :input input-stream
756 :output output-stream
757 :error error-stream
758 :status-hook status-hook
759 :cookie cookie))
760 (push proc *active-processes*))))))))))
761 (dolist (fd *close-in-parent*)
762 (sb-unix:unix-close fd))
763 (unless proc
764 (dolist (fd *close-on-error*)
765 (sb-unix:unix-close fd))
766 (dolist (handler *handlers-installed*)
767 (sb-sys:remove-fd-handler handler))))
768 (when (and wait proc)
769 (process-wait proc))
770 proc))
772 #+win32
773 (defun run-program (program args
774 &key
775 (wait t)
776 search
777 input
778 if-input-does-not-exist
779 output
780 (if-output-exists :error)
781 (error :output)
782 (if-error-exists :error)
783 status-hook)
784 "RUN-PROGRAM creates a new process specified by the PROGRAM
785 argument. ARGS are the standard arguments that can be passed to a
786 program. For no arguments, use NIL (which means that just the name of
787 the program is passed as arg 0).
789 RUN-PROGRAM will return a PROCESS structure. See the CMU
790 Common Lisp Users Manual for details about the PROCESS structure.
792 The &KEY arguments have the following meanings:
793 :SEARCH
794 Look for PROGRAM in each of the directories along the $PATH
795 environment variable. Otherwise an absolute pathname is required.
796 (See also FIND-EXECUTABLE-IN-SEARCH-PATH)
797 :WAIT
798 If non-NIL (default), wait until the created process finishes. If
799 NIL, continue running Lisp until the program finishes.
800 :INPUT
801 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
802 input for the current process is inherited. If NIL, nul
803 is used. If a pathname, the file so specified is used. If a stream,
804 all the input is read from that stream and send to the subprocess. If
805 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
806 its output to the process. Defaults to NIL.
807 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
808 can be one of:
809 :ERROR to generate an error
810 :CREATE to create an empty file
811 NIL (the default) to return NIL from RUN-PROGRAM
812 :OUTPUT
813 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
814 output for the current process is inherited. If NIL, nul
815 is used. If a pathname, the file so specified is used. If a stream,
816 all the output from the process is written to this stream. If
817 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
818 be read to get the output. Defaults to NIL.
819 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
820 can be one of:
821 :ERROR (the default) to generate an error
822 :SUPERSEDE to supersede the file with output from the program
823 :APPEND to append output from the program to the file
824 NIL to return NIL from RUN-PROGRAM, without doing anything
825 :ERROR and :IF-ERROR-EXISTS
826 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
827 specified as :OUTPUT in which case all error output is routed to the
828 same place as normal output.
829 :STATUS-HOOK
830 This is a function the system calls whenever the status of the
831 process changes. The function takes the process as an argument."
832 ;; Prepend the program to the argument list.
833 (push (namestring program) args)
834 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
835 ;; communicate cleanup info.
836 *close-on-error*
837 *close-in-parent*
838 ;; Establish PROC at this level so that we can return it.
839 proc
840 ;; It's friendly to allow the caller to pass any string
841 ;; designator, but internally we'd like SIMPLE-STRINGs.
842 (simple-args
843 (mapcar
844 (lambda (x)
845 (coerce
846 ;; Apparently any spaces or double quotes in the arguments
847 ;; need to be escaped on win32.
848 (if (position-if (lambda (c) (find c '(#\" #\Space))) x)
849 (write-to-string x)
851 'simple-string))
852 args)))
853 (unwind-protect
854 (let ((pfile
855 (if search
856 (find-executable-in-search-path program)
857 (unix-namestring program)))
858 (cookie (list 0)))
859 (unless pfile
860 (error "No such program: ~S" program))
861 (unless (unix-filename-is-executable-p pfile)
862 (error "Not an executable: ~S" program))
863 (multiple-value-bind (stdin input-stream)
864 (get-descriptor-for input cookie
865 :direction :input
866 :if-does-not-exist if-input-does-not-exist)
867 (multiple-value-bind (stdout output-stream)
868 (get-descriptor-for output cookie
869 :direction :output
870 :if-exists if-output-exists)
871 (multiple-value-bind (stderr error-stream)
872 (if (eq error :output)
873 (values stdout output-stream)
874 (get-descriptor-for error cookie
875 :direction :output
876 :if-exists if-error-exists))
877 (with-c-strvec (args-vec simple-args)
878 (let ((handle (without-gcing
879 (spawn pfile args-vec
880 stdin stdout stderr
881 (if wait 1 0)))))
882 (when (= handle -1)
883 (error "Couldn't spawn program: ~A" (strerror)))
884 (setf proc
885 (if wait
886 (make-process :pid handle
887 :%status :exited
888 :input input-stream
889 :output output-stream
890 :error error-stream
891 :status-hook status-hook
892 :cookie cookie
893 :exit-code handle)
894 (make-process :pid handle
895 :%status :running
896 :input input-stream
897 :output output-stream
898 :error error-stream
899 :status-hook status-hook
900 :cookie cookie)))
901 (push proc *active-processes*)))))))
902 (dolist (fd *close-in-parent*)
903 (sb-unix:unix-close fd)))
904 (unless proc
905 (dolist (fd *close-on-error*)
906 (sb-unix:unix-close fd)))
908 proc))
910 ;;; Install a handler for any input that shows up on the file
911 ;;; descriptor. The handler reads the data and writes it to the
912 ;;; stream.
913 (defun copy-descriptor-to-stream (descriptor stream cookie)
914 (incf (car cookie))
915 (let ((string (make-string 256 :element-type 'base-char))
916 handler)
917 (setf handler
918 (sb-sys:add-fd-handler
919 descriptor
920 :input (lambda (fd)
921 (declare (ignore fd))
922 (loop
923 (unless handler
924 (return))
925 (multiple-value-bind
926 (result readable/errno)
927 (sb-unix:unix-select (1+ descriptor)
928 (ash 1 descriptor)
929 0 0 0)
930 (cond ((null result)
931 (error "~@<couldn't select on sub-process: ~
932 ~2I~_~A~:>"
933 (strerror readable/errno)))
934 ((zerop result)
935 (return))))
936 (sb-alien:with-alien ((buf (sb-alien:array
937 sb-alien:char
938 256)))
939 (multiple-value-bind
940 (count errno)
941 (sb-unix:unix-read descriptor
942 (alien-sap buf)
943 256)
944 (cond (#-win32(or (and (null count)
945 (eql errno sb-unix:eio))
946 (eql count 0))
947 #+win32(<= count 0)
948 (sb-sys:remove-fd-handler handler)
949 (setf handler nil)
950 (decf (car cookie))
951 (sb-unix:unix-close descriptor)
952 (return))
953 ((null count)
954 (sb-sys:remove-fd-handler handler)
955 (setf handler nil)
956 (decf (car cookie))
957 (error
958 "~@<couldn't read input from sub-process: ~
959 ~2I~_~A~:>"
960 (strerror errno)))
962 (sb-kernel:copy-ub8-from-system-area
963 (alien-sap buf) 0
964 string 0
965 count)
966 (write-string string stream
967 :end count)))))))))))
969 (defun get-stream-fd (stream direction)
970 (typecase stream
971 (sb-sys:fd-stream
972 (values (sb-sys:fd-stream-fd stream) nil))
973 (synonym-stream
974 (get-stream-fd (symbol-value (synonym-stream-symbol stream)) direction))
975 (two-way-stream
976 (ecase direction
977 (:input
978 (get-stream-fd (two-way-stream-input-stream stream) direction))
979 (:output
980 (get-stream-fd (two-way-stream-output-stream stream) direction))))))
982 ;;; Find a file descriptor to use for object given the direction.
983 ;;; Returns the descriptor. If object is :STREAM, returns the created
984 ;;; stream as the second value.
985 (defun get-descriptor-for (object
986 cookie
987 &rest keys
988 &key direction
989 &allow-other-keys)
990 (cond ((eq object t)
991 ;; No new descriptor is needed.
992 (values -1 nil))
993 ((eq object nil)
994 ;; Use /dev/null.
995 (multiple-value-bind
996 (fd errno)
997 (sb-unix:unix-open #-win32 #.(coerce "/dev/null" 'base-string)
998 #+win32 #.(coerce "nul" 'base-string)
999 (case direction
1000 (:input sb-unix:o_rdonly)
1001 (:output sb-unix:o_wronly)
1002 (t sb-unix:o_rdwr))
1003 #o666)
1004 (unless fd
1005 (error #-win32 "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
1006 #+win32 "~@<couldn't open \"nul\" device: ~2I~_~A~:>"
1007 (strerror errno)))
1008 (push fd *close-in-parent*)
1009 (values fd nil)))
1010 ((eq object :stream)
1011 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
1012 (unless read-fd
1013 (error "couldn't create pipe: ~A" (strerror write-fd)))
1014 (case direction
1015 (:input
1016 (push read-fd *close-in-parent*)
1017 (push write-fd *close-on-error*)
1018 (let ((stream (sb-sys:make-fd-stream write-fd :output t
1019 :element-type :default)))
1020 (values read-fd stream)))
1021 (:output
1022 (push read-fd *close-on-error*)
1023 (push write-fd *close-in-parent*)
1024 (let ((stream (sb-sys:make-fd-stream read-fd :input t
1025 :element-type :default)))
1026 (values write-fd stream)))
1028 (sb-unix:unix-close read-fd)
1029 (sb-unix:unix-close write-fd)
1030 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
1031 direction)))))
1032 ((or (pathnamep object) (stringp object))
1033 (with-open-stream (file (apply #'open object keys))
1034 (multiple-value-bind
1035 (fd errno)
1036 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
1037 (cond (fd
1038 (push fd *close-in-parent*)
1039 (values fd nil))
1041 (error "couldn't duplicate file descriptor: ~A"
1042 (strerror errno)))))))
1043 ((streamp object)
1044 (ecase direction
1045 (:input
1046 (or (get-stream-fd object :input)
1047 ;; FIXME: We could use a better way of setting up
1048 ;; temporary files
1049 (dotimes (count
1051 (error "could not open a temporary file in /tmp"))
1052 (let* ((name (coerce (format nil "/tmp/.run-program-~D" count)
1053 'base-string))
1054 (fd (sb-unix:unix-open name
1055 (logior sb-unix:o_rdwr
1056 sb-unix:o_creat
1057 sb-unix:o_excl)
1058 #o666)))
1059 (sb-unix:unix-unlink name)
1060 (when fd
1061 (let ((newline (string #\Newline)))
1062 (loop
1063 (multiple-value-bind
1064 (line no-cr)
1065 (read-line object nil nil)
1066 (unless line
1067 (return))
1068 (sb-unix:unix-write
1070 ;; FIXME: this really should be
1071 ;; (STRING-TO-OCTETS :EXTERNAL-FORMAT ...).
1072 ;; RUN-PROGRAM should take an
1073 ;; external-format argument, which should
1074 ;; be passed down to here. Something
1075 ;; similar should happen on :OUTPUT, too.
1076 (map '(vector (unsigned-byte 8)) #'char-code line)
1077 0 (length line))
1078 (if no-cr
1079 (return)
1080 (sb-unix:unix-write fd newline 0 1)))))
1081 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
1082 (push fd *close-in-parent*)
1083 (return (values fd nil)))))))
1084 (:output
1085 (or (get-stream-fd object :output)
1086 (multiple-value-bind (read-fd write-fd)
1087 (sb-unix:unix-pipe)
1088 (unless read-fd
1089 (error "couldn't create pipe: ~S" (strerror write-fd)))
1090 (copy-descriptor-to-stream read-fd object cookie)
1091 (push read-fd *close-on-error*)
1092 (push write-fd *close-in-parent*)
1093 (values write-fd nil))))))
1095 (error "invalid option to RUN-PROGRAM: ~S" object))))