0.7.13.3
[sbcl/lichteblau.git] / src / code / run-program.lisp
blob9153a8f2cbe1193cfa17803991884a84edc7b4bd
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 (define-alien-routine wrapped-environ (* c-string))
49 (defun posix-environ ()
50 "Return the Unix environment (\"man environ\") as a list of SIMPLE-STRINGs."
51 (c-strings->string-list (wrapped-environ)))
53 ;;; Convert as best we can from an SBCL representation of a Unix
54 ;;; environment to a CMU CL representation.
55 ;;;
56 ;;; * (UNIX-ENVIRONMENT-CMUCL-FROM-SBCL '("Bletch=fub" "Noggin" "YES=No!"))
57 ;;; WARNING:
58 ;;; smashing case of "Bletch=fub" in conversion to CMU-CL-style
59 ;;; environment alist
60 ;;; WARNING:
61 ;;; no #\= in "Noggin", eliding it in CMU-CL-style environment alist
62 ;;; ((:BLETCH . "fub") (:YES . "No!"))
63 (defun unix-environment-cmucl-from-sbcl (sbcl)
64 (mapcan
65 (lambda (string)
66 (declare (type simple-string string))
67 (let ((=-pos (position #\= string :test #'equal)))
68 (if =-pos
69 (list
70 (let* ((key-as-string (subseq string 0 =-pos))
71 (key-as-upcase-string (string-upcase key-as-string))
72 (key (keywordicate key-as-upcase-string))
73 (val (subseq string (1+ =-pos))))
74 (unless (string= key-as-string key-as-upcase-string)
75 (warn "smashing case of ~S in conversion to CMU-CL-style ~
76 environment alist"
77 string))
78 (cons key val)))
79 (warn "no #\\= in ~S, eliding it in CMU-CL-style environment alist"
80 string))))
81 sbcl))
83 ;;; Convert from a CMU CL representation of a Unix environment to a
84 ;;; SBCL representation.
85 (defun unix-environment-sbcl-from-cmucl (cmucl)
86 (mapcar
87 (lambda (cons)
88 (destructuring-bind (key . val) cons
89 (declare (type keyword key) (type simple-string val))
90 (concatenate 'simple-string (symbol-name key) "=" val)))
91 cmucl))
93 ;;;; Import wait3(2) from Unix.
95 (define-alien-routine ("wait3" c-wait3) sb-alien:int
96 (status sb-alien:int :out)
97 (options sb-alien:int)
98 (rusage sb-alien:int))
100 (defun wait3 (&optional do-not-hang check-for-stopped)
101 "Return any available status information on child process. "
102 (multiple-value-bind (pid status)
103 (c-wait3 (logior (if do-not-hang
104 sb-unix:wnohang
106 (if check-for-stopped
107 sb-unix:wuntraced
110 (cond ((or (minusp pid)
111 (zerop pid))
112 nil)
113 ((eql (ldb (byte 8 0) status)
114 sb-unix:wstopped)
115 (values pid
116 :stopped
117 (ldb (byte 8 8) status)))
118 ((zerop (ldb (byte 7 0) status))
119 (values pid
120 :exited
121 (ldb (byte 8 8) status)))
123 (let ((signal (ldb (byte 7 0) status)))
124 (values pid
125 (if (position signal
126 #.(vector
127 (sb-unix:unix-signal-number :sigstop)
128 (sb-unix:unix-signal-number :sigtstp)
129 (sb-unix:unix-signal-number :sigttin)
130 (sb-unix:unix-signal-number :sigttou)))
131 :stopped
132 :signaled)
133 signal
134 (not (zerop (ldb (byte 1 7) status)))))))))
136 ;;;; process control stuff
138 (defvar *active-processes* nil
139 "List of process structures for all active processes.")
141 (defstruct (process (:copier nil))
142 pid ; PID of child process
143 %status ; either :RUNNING, :STOPPED, :EXITED, or :SIGNALED
144 exit-code ; either exit code or signal
145 core-dumped ; T if a core image was dumped
146 pty ; stream to child's pty, or NIL
147 input ; stream to child's input, or NIL
148 output ; stream from child's output, or NIL
149 error ; stream from child's error output, or NIL
150 status-hook ; closure to call when PROC changes status
151 plist ; a place for clients to stash things
152 cookie) ; list of the number of pipes from the subproc
154 (defmethod print-object ((process process) stream)
155 (print-unreadable-object (process stream :type t)
156 (format stream
157 "~W ~S"
158 (process-pid process)
159 (process-status process)))
160 process)
162 (defun process-status (proc)
163 "Return the current status of process. The result is one of :RUNNING,
164 :STOPPED, :EXITED, or :SIGNALED."
165 (get-processes-status-changes)
166 (process-%status proc))
168 (defun process-wait (proc &optional check-for-stopped)
169 "Wait for PROC to quit running for some reason. Returns PROC."
170 (loop
171 (case (process-status proc)
172 (:running)
173 (:stopped
174 (when check-for-stopped
175 (return)))
177 (when (zerop (car (process-cookie proc)))
178 (return))))
179 (sb-sys:serve-all-events 1))
180 proc)
182 #-hpux
183 ;;; Find the current foreground process group id.
184 (defun find-current-foreground-process (proc)
185 (with-alien ((result sb-alien:int))
186 (multiple-value-bind
187 (wonp error)
188 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
189 sb-unix:TIOCGPGRP
190 (alien-sap (sb-alien:addr result)))
191 (unless wonp
192 (error "TIOCPGRP ioctl failed: ~S" (strerror error)))
193 result))
194 (process-pid proc))
196 (defun process-kill (proc signal &optional (whom :pid))
197 "Hand SIGNAL to PROC. If WHOM is :PID, use the kill Unix system call. If
198 WHOM is :PROCESS-GROUP, use the killpg Unix system call. If WHOM is
199 :PTY-PROCESS-GROUP deliver the signal to whichever process group is
200 currently in the foreground."
201 (let ((pid (ecase whom
202 ((:pid :process-group)
203 (process-pid proc))
204 (:pty-process-group
205 #-hpux
206 (find-current-foreground-process proc)))))
207 (multiple-value-bind
208 (okay errno)
209 (case whom
210 #+hpux
211 (:pty-process-group
212 (sb-unix:unix-ioctl (sb-sys:fd-stream-fd (process-pty proc))
213 sb-unix:TIOCSIGSEND
214 (sb-sys:int-sap
215 (sb-unix:unix-signal-number signal))))
216 ((:process-group #-hpux :pty-process-group)
217 (sb-unix:unix-killpg pid signal))
219 (sb-unix:unix-kill pid signal)))
220 (cond ((not okay)
221 (values nil errno))
222 ((and (eql pid (process-pid proc))
223 (= (sb-unix:unix-signal-number signal)
224 (sb-unix:unix-signal-number :sigcont)))
225 (setf (process-%status proc) :running)
226 (setf (process-exit-code proc) nil)
227 (when (process-status-hook proc)
228 (funcall (process-status-hook proc) proc))
231 t)))))
233 (defun process-alive-p (proc)
234 "Return T if the process is still alive, NIL otherwise."
235 (let ((status (process-status proc)))
236 (if (or (eq status :running)
237 (eq status :stopped))
239 nil)))
241 (defun process-close (proc)
242 "Close all streams connected to PROC and stop maintaining the status slot."
243 (macrolet ((frob (stream abort)
244 `(when ,stream (close ,stream :abort ,abort))))
245 (frob (process-pty proc) t) ; Don't FLUSH-OUTPUT to dead process, ..
246 (frob (process-input proc) t) ; .. 'cause it will generate SIGPIPE.
247 (frob (process-output proc) nil)
248 (frob (process-error proc) nil))
249 (sb-sys:without-interrupts
250 (setf *active-processes* (delete proc *active-processes*)))
251 proc)
253 ;;; the handler for SIGCHLD signals that RUN-PROGRAM establishes
254 (defun sigchld-handler (ignore1 ignore2 ignore3)
255 (declare (ignore ignore1 ignore2 ignore3))
256 (get-processes-status-changes))
258 (defun get-processes-status-changes ()
259 (loop
260 (multiple-value-bind (pid what code core)
261 (wait3 t t)
262 (unless pid
263 (return))
264 (let ((proc (find pid *active-processes* :key #'process-pid)))
265 (when proc
266 (setf (process-%status proc) what)
267 (setf (process-exit-code proc) code)
268 (setf (process-core-dumped proc) core)
269 (when (process-status-hook proc)
270 (funcall (process-status-hook proc) proc))
271 (when (position what #(:exited :signaled))
272 (sb-sys:without-interrupts
273 (setf *active-processes*
274 (delete proc *active-processes*)))))))))
276 ;;;; RUN-PROGRAM and close friends
278 ;;; list of file descriptors to close when RUN-PROGRAM exits due to an error
279 (defvar *close-on-error* nil)
281 ;;; list of file descriptors to close when RUN-PROGRAM returns in the parent
282 (defvar *close-in-parent* nil)
284 ;;; list of handlers installed by RUN-PROGRAM
285 (defvar *handlers-installed* nil)
287 ;;; Find an unused pty. Return three values: the file descriptor for
288 ;;; the master side of the pty, the file descriptor for the slave side
289 ;;; of the pty, and the name of the tty device for the slave side.
290 (defun find-a-pty ()
291 (dolist (char '(#\p #\q))
292 (dotimes (digit 16)
293 (let* ((master-name (format nil "/dev/pty~C~X" char digit))
294 (master-fd (sb-unix:unix-open master-name
295 sb-unix:o_rdwr
296 #o666)))
297 (when master-fd
298 (let* ((slave-name (format nil "/dev/tty~C~X" char digit))
299 (slave-fd (sb-unix:unix-open slave-name
300 sb-unix:o_rdwr
301 #o666)))
302 (when slave-fd
303 (return-from find-a-pty
304 (values master-fd
305 slave-fd
306 slave-name)))
307 (sb-unix:unix-close master-fd))))))
308 (error "could not find a pty"))
310 (defun open-pty (pty cookie)
311 (when pty
312 (multiple-value-bind
313 (master slave name)
314 (find-a-pty)
315 (push master *close-on-error*)
316 (push slave *close-in-parent*)
317 (when (streamp pty)
318 (multiple-value-bind (new-fd errno) (sb-unix:unix-dup master)
319 (unless new-fd
320 (error "couldn't SB-UNIX:UNIX-DUP ~W: ~A" master (strerror errno)))
321 (push new-fd *close-on-error*)
322 (copy-descriptor-to-stream new-fd pty cookie)))
323 (values name
324 (sb-sys:make-fd-stream master :input t :output t)))))
326 (defmacro round-bytes-to-words (n)
327 `(logand (the fixnum (+ (the fixnum ,n) 3)) (lognot 3)))
329 (defun string-list-to-c-strvec (string-list)
330 ;; Make a pass over STRING-LIST to calculate the amount of memory
331 ;; needed to hold the strvec.
332 (let ((string-bytes 0)
333 ;; We need an extra for the null, and an extra 'cause exect
334 ;; clobbers argv[-1].
335 (vec-bytes (* #-alpha 4 #+alpha 8 (+ (length string-list) 2))))
336 (declare (fixnum string-bytes vec-bytes))
337 (dolist (s string-list)
338 (enforce-type s simple-string)
339 (incf string-bytes (round-bytes-to-words (1+ (length s)))))
340 ;; Now allocate the memory and fill it in.
341 (let* ((total-bytes (+ string-bytes vec-bytes))
342 (vec-sap (sb-sys:allocate-system-memory total-bytes))
343 (string-sap (sap+ vec-sap vec-bytes))
344 (i #-alpha 4 #+alpha 8))
345 (declare (type (and unsigned-byte fixnum) total-bytes i)
346 (type sb-sys:system-area-pointer vec-sap string-sap))
347 (dolist (s string-list)
348 (declare (simple-string s))
349 (let ((n (length s)))
350 ;; Blast the string into place.
351 (sb-kernel:copy-to-system-area (the simple-string s)
352 (* sb-vm:vector-data-offset
353 sb-vm:n-word-bits)
354 string-sap 0
355 (* (1+ n) sb-vm:n-byte-bits))
356 ;; Blast the pointer to the string into place.
357 (setf (sap-ref-sap vec-sap i) string-sap)
358 (setf string-sap (sap+ string-sap (round-bytes-to-words (1+ n))))
359 (incf i #-alpha 4 #+alpha 8)))
360 ;; Blast in the last null pointer.
361 (setf (sap-ref-sap vec-sap i) (int-sap 0))
362 (values vec-sap (sap+ vec-sap #-alpha 4 #+alpha 8) total-bytes))))
364 (defmacro with-c-strvec ((var str-list) &body body)
365 (let ((sap (gensym "SAP-"))
366 (size (gensym "SIZE-")))
367 `(multiple-value-bind
368 (,sap ,var ,size)
369 (string-list-to-c-strvec ,str-list)
370 (unwind-protect
371 (progn
372 ,@body)
373 (sb-sys:deallocate-system-memory ,sap ,size)))))
375 (sb-alien:define-alien-routine spawn sb-alien:int
376 (program sb-alien:c-string)
377 (argv (* sb-alien:c-string))
378 (envp (* sb-alien:c-string))
379 (pty-name sb-alien:c-string)
380 (stdin sb-alien:int)
381 (stdout sb-alien:int)
382 (stderr sb-alien:int))
384 ;;; Is UNIX-FILENAME the name of a file that we can execute?
385 ;;; XXX does this actually work for symlinks?
386 (defun unix-filename-is-executable-p (unix-filename)
387 (declare (type simple-string unix-filename))
388 (values (and (eq (sb-unix:unix-file-kind unix-filename) :file)
389 (sb-unix:unix-access unix-filename sb-unix:x_ok))))
391 ;;; FIXME: There shouldn't be two semiredundant versions of the
392 ;;; documentation. Since this is a public extension function, the
393 ;;; documentation should be in the doc string. So all information from
394 ;;; this comment should be merged into the doc string, and then this
395 ;;; comment can go away.
397 ;;; RUN-PROGRAM uses fork() and execve() to run a different program.
398 ;;; Strange stuff happens to keep the Unix state of the world
399 ;;; coherent.
401 ;;; The child process needs to get its input from somewhere, and send
402 ;;; its output (both standard and error) to somewhere. We have to do
403 ;;; different things depending on where these somewheres really are.
405 ;;; For input, there are five options:
406 ;;; -- T: Just leave fd 0 alone. Pretty simple.
407 ;;; -- "file": Read from the file. We need to open the file and
408 ;;; pull the descriptor out of the stream. The parent should close
409 ;;; this stream after the child is up and running to free any
410 ;;; storage used in the parent.
411 ;;; -- NIL: Same as "file", but use "/dev/null" as the file.
412 ;;; -- :STREAM: Use Unix pipe() to create two descriptors. Use
413 ;;; SB-SYS:MAKE-FD-STREAM to create the output stream on the
414 ;;; writeable descriptor, and pass the readable descriptor to
415 ;;; the child. The parent must close the readable descriptor for
416 ;;; EOF to be passed up correctly.
417 ;;; -- a stream: If it's a fd-stream, just pull the descriptor out
418 ;;; of it. Otherwise make a pipe as in :STREAM, and copy
419 ;;; everything across.
421 ;;; For output, there are five options:
422 ;;; -- T: Leave descriptor 1 alone.
423 ;;; -- "file": dump output to the file.
424 ;;; -- NIL: dump output to /dev/null.
425 ;;; -- :STREAM: return a stream that can be read from.
426 ;;; -- a stream: if it's a fd-stream, use the descriptor in it.
427 ;;; Otherwise, copy stuff from output to stream.
429 ;;; For error, there are all the same options as output plus:
430 ;;; -- :OUTPUT: redirect to the same place as output.
432 ;;; RUN-PROGRAM returns a PROCESS structure for the process if
433 ;;; the fork worked, and NIL if it did not.
434 (defun run-program (program args
435 &key
436 (env nil env-p)
437 (environment (if env-p
438 (unix-environment-sbcl-from-cmucl env)
439 (posix-environ))
440 environment-p)
441 (wait t)
443 input
444 if-input-does-not-exist
445 output
446 (if-output-exists :error)
447 (error :output)
448 (if-error-exists :error)
449 status-hook)
450 "RUN-PROGRAM creates a new Unix process running the Unix program found in
451 the file specified by the PROGRAM argument. ARGS are the standard
452 arguments that can be passed to a Unix program. For no arguments, use NIL
453 (which means that just the name of the program is passed as arg 0).
455 RUN-PROGRAM will either return NIL or a PROCESS structure. See the CMU
456 Common Lisp Users Manual for details about the PROCESS structure.
458 notes about Unix environments (as in the :ENVIRONMENT and :ENV args):
459 1. The SBCL implementation of RUN-PROGRAM, like Perl and many other
460 programs, but unlike the original CMU CL implementation, copies
461 the Unix environment by default.
462 2. Running Unix programs from a setuid process, or in any other
463 situation where the Unix environment is under the control of someone
464 else, is a mother lode of security problems. If you are contemplating
465 doing this, read about it first. (The Perl community has a lot of good
466 documentation about this and other security issues in script-like
467 programs.)
469 The &KEY arguments have the following meanings:
470 :ENVIRONMENT
471 a list of SIMPLE-STRINGs describing the new Unix environment (as
472 in \"man environ\"). The default is to copy the environment of
473 the current process.
474 :ENV
475 an alternative lossy representation of the new Unix environment,
476 for compatibility with CMU CL
477 :WAIT
478 If non-NIL (default), wait until the created process finishes. If
479 NIL, continue running Lisp until the program finishes.
480 :PTY
481 Either T, NIL, or a stream. Unless NIL, the subprocess is established
482 under a PTY. If :pty is a stream, all output to this pty is sent to
483 this stream, otherwise the PROCESS-PTY slot is filled in with a stream
484 connected to pty that can read output and write input.
485 :INPUT
486 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
487 input for the current process is inherited. If NIL, /dev/null
488 is used. If a pathname, the file so specified is used. If a stream,
489 all the input is read from that stream and send to the subprocess. If
490 :STREAM, the PROCESS-INPUT slot is filled in with a stream that sends
491 its output to the process. Defaults to NIL.
492 :IF-INPUT-DOES-NOT-EXIST (when :INPUT is the name of a file)
493 can be one of:
494 :ERROR to generate an error
495 :CREATE to create an empty file
496 NIL (the default) to return NIL from RUN-PROGRAM
497 :OUTPUT
498 Either T, NIL, a pathname, a stream, or :STREAM. If T, the standard
499 output for the current process is inherited. If NIL, /dev/null
500 is used. If a pathname, the file so specified is used. If a stream,
501 all the output from the process is written to this stream. If
502 :STREAM, the PROCESS-OUTPUT slot is filled in with a stream that can
503 be read to get the output. Defaults to NIL.
504 :IF-OUTPUT-EXISTS (when :OUTPUT is the name of a file)
505 can be one of:
506 :ERROR (the default) to generate an error
507 :SUPERSEDE to supersede the file with output from the program
508 :APPEND to append output from the program to the file
509 NIL to return NIL from RUN-PROGRAM, without doing anything
510 :ERROR and :IF-ERROR-EXISTS
511 Same as :OUTPUT and :IF-OUTPUT-EXISTS, except that :ERROR can also be
512 specified as :OUTPUT in which case all error output is routed to the
513 same place as normal output.
514 :STATUS-HOOK
515 This is a function the system calls whenever the status of the
516 process changes. The function takes the process as an argument."
518 (when (and env-p environment-p)
519 (error "can't specify :ENV and :ENVIRONMENT simultaneously"))
520 ;; Make sure that the interrupt handler is installed.
521 (sb-sys:enable-interrupt :sigchld #'sigchld-handler)
522 ;; Prepend the program to the argument list.
523 (push (namestring program) args)
524 (let (;; Clear various specials used by GET-DESCRIPTOR-FOR to
525 ;; communicate cleanup info.
526 *close-on-error*
527 *close-in-parent*
528 *handlers-installed*
529 ;; Establish PROC at this level so that we can return it.
530 proc
531 ;; It's friendly to allow the caller to pass any string
532 ;; designator, but internally we'd like SIMPLE-STRINGs.
533 (simple-args (mapcar (lambda (x) (coerce x 'simple-string)) args)))
534 (unwind-protect
535 (let (;; FIXME: The old code here used to do
536 ;; (MERGE-PATHNAMES PROGRAM "path:"),
537 ;; which is the right idea (searching through the Unix
538 ;; PATH). Unfortunately, there is no logical pathname
539 ;; "path:" defined in sbcl-0.6.10. It would probably be
540 ;; reasonable to restore Unix PATH searching in SBCL, e.g.
541 ;; with a function FIND-EXECUTABLE-FILE-IN-POSIX-PATH.
542 ;; CMU CL did it with a "PATH:" search list, but CMU CL
543 ;; search lists are a non-ANSI extension that SBCL
544 ;; doesn't support. -- WHN)
545 (pfile (unix-namestring program t))
546 (cookie (list 0)))
547 (unless pfile
548 (error "no such program: ~S" program))
549 (unless (unix-filename-is-executable-p pfile)
550 (error "not executable: ~S" program))
551 (multiple-value-bind (stdin input-stream)
552 (get-descriptor-for input cookie
553 :direction :input
554 :if-does-not-exist if-input-does-not-exist)
555 (multiple-value-bind (stdout output-stream)
556 (get-descriptor-for output cookie
557 :direction :output
558 :if-exists if-output-exists)
559 (multiple-value-bind (stderr error-stream)
560 (if (eq error :output)
561 (values stdout output-stream)
562 (get-descriptor-for error cookie
563 :direction :output
564 :if-exists if-error-exists))
565 (multiple-value-bind (pty-name pty-stream)
566 (open-pty pty cookie)
567 ;; Make sure we are not notified about the child
568 ;; death before we have installed the PROCESS
569 ;; structure in *ACTIVE-PROCESSES*.
570 (sb-sys:without-interrupts
571 (with-c-strvec (args-vec simple-args)
572 (with-c-strvec (environment-vec environment)
573 (let ((child-pid
574 (without-gcing
575 (spawn pfile args-vec environment-vec pty-name
576 stdin stdout stderr))))
577 (when (< child-pid 0)
578 (error "couldn't fork child process: ~A"
579 (strerror)))
580 (setf proc (make-process :pid child-pid
581 :%status :running
582 :pty pty-stream
583 :input input-stream
584 :output output-stream
585 :error error-stream
586 :status-hook status-hook
587 :cookie cookie))
588 (push proc *active-processes*))))))))))
589 (dolist (fd *close-in-parent*)
590 (sb-unix:unix-close fd))
591 (unless proc
592 (dolist (fd *close-on-error*)
593 (sb-unix:unix-close fd))
594 (dolist (handler *handlers-installed*)
595 (sb-sys:remove-fd-handler handler))))
596 (when (and wait proc)
597 (process-wait proc))
598 proc))
600 ;;; Install a handler for any input that shows up on the file
601 ;;; descriptor. The handler reads the data and writes it to the
602 ;;; stream.
603 (defun copy-descriptor-to-stream (descriptor stream cookie)
604 (incf (car cookie))
605 (let ((string (make-string 256))
606 handler)
607 (setf handler
608 (sb-sys:add-fd-handler
609 descriptor
610 :input (lambda (fd)
611 (declare (ignore fd))
612 (loop
613 (unless handler
614 (return))
615 (multiple-value-bind
616 (result readable/errno)
617 (sb-unix:unix-select (1+ descriptor)
618 (ash 1 descriptor)
619 0 0 0)
620 (cond ((null result)
621 (error "~@<couldn't select on sub-process: ~
622 ~2I~_~A~:>"
623 (strerror readable/errno)))
624 ((zerop result)
625 (return))))
626 (sb-alien:with-alien ((buf (sb-alien:array
627 sb-alien:char
628 256)))
629 (multiple-value-bind
630 (count errno)
631 (sb-unix:unix-read descriptor
632 (alien-sap buf)
633 256)
634 (cond ((or (and (null count)
635 (eql errno sb-unix:eio))
636 (eql count 0))
637 (sb-sys:remove-fd-handler handler)
638 (setf handler nil)
639 (decf (car cookie))
640 (sb-unix:unix-close descriptor)
641 (return))
642 ((null count)
643 (sb-sys:remove-fd-handler handler)
644 (setf handler nil)
645 (decf (car cookie))
646 (error
647 "~@<couldn't read input from sub-process: ~
648 ~2I~_~A~:>"
649 (strerror errno)))
651 (sb-kernel:copy-from-system-area
652 (alien-sap buf) 0
653 string (* sb-vm:vector-data-offset
654 sb-vm:n-word-bits)
655 (* count sb-vm:n-byte-bits))
656 (write-string string stream
657 :end count)))))))))))
659 ;;; Find a file descriptor to use for object given the direction.
660 ;;; Returns the descriptor. If object is :STREAM, returns the created
661 ;;; stream as the second value.
662 (defun get-descriptor-for (object
663 cookie
664 &rest keys
665 &key direction
666 &allow-other-keys)
667 (cond ((eq object t)
668 ;; No new descriptor is needed.
669 (values -1 nil))
670 ((eq object nil)
671 ;; Use /dev/null.
672 (multiple-value-bind
673 (fd errno)
674 (sb-unix:unix-open "/dev/null"
675 (case direction
676 (:input sb-unix:o_rdonly)
677 (:output sb-unix:o_wronly)
678 (t sb-unix:o_rdwr))
679 #o666)
680 (unless fd
681 (error "~@<couldn't open \"/dev/null\": ~2I~_~A~:>"
682 (strerror errno)))
683 (push fd *close-in-parent*)
684 (values fd nil)))
685 ((eq object :stream)
686 (multiple-value-bind (read-fd write-fd) (sb-unix:unix-pipe)
687 (unless read-fd
688 (error "couldn't create pipe: ~A" (strerror write-fd)))
689 (case direction
690 (:input
691 (push read-fd *close-in-parent*)
692 (push write-fd *close-on-error*)
693 (let ((stream (sb-sys:make-fd-stream write-fd :output t)))
694 (values read-fd stream)))
695 (:output
696 (push read-fd *close-on-error*)
697 (push write-fd *close-in-parent*)
698 (let ((stream (sb-sys:make-fd-stream read-fd :input t)))
699 (values write-fd stream)))
701 (sb-unix:unix-close read-fd)
702 (sb-unix:unix-close write-fd)
703 (error "Direction must be either :INPUT or :OUTPUT, not ~S."
704 direction)))))
705 ((or (pathnamep object) (stringp object))
706 (with-open-stream (file (apply #'open object keys))
707 (multiple-value-bind
708 (fd errno)
709 (sb-unix:unix-dup (sb-sys:fd-stream-fd file))
710 (cond (fd
711 (push fd *close-in-parent*)
712 (values fd nil))
714 (error "couldn't duplicate file descriptor: ~A"
715 (strerror errno)))))))
716 ((sb-sys:fd-stream-p object)
717 (values (sb-sys:fd-stream-fd object) nil))
718 ((streamp object)
719 (ecase direction
720 (:input
721 ;; FIXME: We could use a better way of setting up
722 ;; temporary files, both here and in LOAD-FOREIGN.
723 (dotimes (count
725 (error "could not open a temporary file in /tmp"))
726 (let* ((name (format nil "/tmp/.run-program-~D" count))
727 (fd (sb-unix:unix-open name
728 (logior sb-unix:o_rdwr
729 sb-unix:o_creat
730 sb-unix:o_excl)
731 #o666)))
732 (sb-unix:unix-unlink name)
733 (when fd
734 (let ((newline (string #\Newline)))
735 (loop
736 (multiple-value-bind
737 (line no-cr)
738 (read-line object nil nil)
739 (unless line
740 (return))
741 (sb-unix:unix-write fd line 0 (length line))
742 (if no-cr
743 (return)
744 (sb-unix:unix-write fd newline 0 1)))))
745 (sb-unix:unix-lseek fd 0 sb-unix:l_set)
746 (push fd *close-in-parent*)
747 (return (values fd nil))))))
748 (:output
749 (multiple-value-bind (read-fd write-fd)
750 (sb-unix:unix-pipe)
751 (unless read-fd
752 (error "couldn't create pipe: ~S" (strerror write-fd)))
753 (copy-descriptor-to-stream read-fd object cookie)
754 (push read-fd *close-on-error*)
755 (push write-fd *close-in-parent*)
756 (values write-fd nil)))))
758 (error "invalid option to RUN-PROGRAM: ~S" object))))