1 ! Copyright (C) 2007, 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types arrays assocs combinators
4 continuations environment io io.backend io.backend.unix
5 io.files io.files.private io.files.unix io.launcher
6 io.launcher.unix.parser io.pathnames io.ports kernel math
7 namespaces sequences strings system threads unix unix
14 : get-arguments ( process -- seq )
15 command>> dup string? [ tokenize-command ] when ;
17 : assoc>env ( assoc -- env )
18 [ "=" glue ] { } assoc>map ;
20 : setup-priority ( process -- process )
23 { +lowest-priority+ 20 }
25 { +normal-priority+ 0 }
26 { +high-priority+ -10 }
27 { +highest-priority+ -20 }
28 { +realtime-priority+ -20 }
33 [ F_SETFL 0 fcntl io-error ] [ F_SETFD 0 fcntl io-error ] bi ;
35 : redirect-fd ( oldfd fd -- )
36 2dup = [ 2drop ] [ dup2 io-error ] if ;
38 : redirect-file ( obj mode fd -- )
39 [ [ normalize-path ] dip file-mode open-file ] dip redirect-fd ;
41 : redirect-file-append ( obj mode fd -- )
42 [ drop path>> normalize-path open-append ] dip redirect-fd ;
44 : redirect-closed ( obj mode fd -- )
45 [ drop "/dev/null" ] 2dip redirect-file ;
47 : redirect ( obj mode fd -- )
49 { [ pick not ] [ 3drop ] }
50 { [ pick string? ] [ redirect-file ] }
51 { [ pick appender? ] [ redirect-file-append ] }
52 { [ pick +closed+ eq? ] [ redirect-closed ] }
53 { [ pick fd? ] [ [ drop fd>> dup reset-fd ] dip redirect-fd ] }
54 [ [ underlying-handle ] 2dip redirect ]
57 : ?closed ( obj -- obj' )
58 dup +closed+ eq? [ drop "/dev/null" ] when ;
60 : setup-redirection ( process -- process )
61 dup stdin>> ?closed read-flags 0 redirect
62 dup stdout>> ?closed write-flags 1 redirect
63 dup stderr>> dup +stdout+ eq? [
64 drop 1 2 dup2 io-error
66 ?closed write-flags 2 redirect
69 : setup-environment ( process -- process )
70 dup pass-environment? [
71 dup get-environment set-os-envs
74 : spawn-process ( process -- * )
75 [ setup-priority ] [ 250 _exit ] recover
76 [ setup-redirection ] [ 251 _exit ] recover
77 [ current-directory get (normalize-path) cd ] [ 252 _exit ] recover
78 [ setup-environment ] [ 253 _exit ] recover
79 [ get-arguments exec-args-with-path ] [ 254 _exit ] recover
82 M: unix current-process-handle ( -- handle ) getpid ;
84 M: unix run-process* ( process -- pid )
85 [ spawn-process ] curry [ ] with-fork ;
87 M: unix kill-process* ( pid -- )
88 SIGTERM kill io-error ;
90 : find-process ( handle -- process )
91 processes get swap [ nip swap handle>> = ] curry
96 : code>status ( code -- obj )
97 dup WIFEXITED [ WEXITSTATUS ] [ WTERMSIG signal boa ] if ;
99 M: unix wait-for-processes ( -- ? )
100 0 <int> -1 over WNOHANG waitpid
105 [ swap *int code>status notify-exit f ] [ 2drop f ] if