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
11 : get-arguments ( process -- seq )
12 command>> dup string? [ tokenize-command ] when ;
14 : assoc>env ( assoc -- env )
15 [ "=" glue ] { } assoc>map ;
17 : setup-priority ( process -- process )
20 { +lowest-priority+ 20 }
22 { +normal-priority+ 0 }
23 { +high-priority+ -10 }
24 { +highest-priority+ -20 }
25 { +realtime-priority+ -20 }
30 [ F_SETFL 0 fcntl io-error ] [ F_SETFD 0 fcntl io-error ] bi ;
32 : redirect-fd ( oldfd fd -- )
33 2dup = [ 2drop ] [ dup2 io-error ] if ;
35 : redirect-file ( obj mode fd -- )
36 [ [ normalize-path ] dip file-mode open-file ] dip redirect-fd ;
38 : redirect-file-append ( obj mode fd -- )
39 [ drop path>> normalize-path open-append ] dip redirect-fd ;
41 : redirect-closed ( obj mode fd -- )
42 [ drop "/dev/null" ] 2dip redirect-file ;
44 : redirect ( obj mode fd -- )
46 { [ pick not ] [ 3drop ] }
47 { [ pick string? ] [ redirect-file ] }
48 { [ pick appender? ] [ redirect-file-append ] }
49 { [ pick +closed+ eq? ] [ redirect-closed ] }
50 { [ pick fd? ] [ [ drop fd>> dup reset-fd ] dip redirect-fd ] }
51 [ [ underlying-handle ] 2dip redirect ]
54 : ?closed ( obj -- obj' )
55 dup +closed+ eq? [ drop "/dev/null" ] when ;
57 : setup-redirection ( process -- process )
58 dup stdin>> ?closed read-flags 0 redirect
59 dup stdout>> ?closed write-flags 1 redirect
60 dup stderr>> dup +stdout+ eq? [
61 drop 1 2 dup2 io-error
63 ?closed write-flags 2 redirect
66 : setup-environment ( process -- process )
67 dup pass-environment? [
68 dup get-environment set-os-envs
71 : spawn-process ( process -- * )
72 [ setup-priority ] [ 250 _exit ] recover
73 [ setup-redirection ] [ 251 _exit ] recover
74 [ current-directory get absolute-path cd ] [ 252 _exit ] recover
75 [ setup-environment ] [ 253 _exit ] recover
76 [ get-arguments exec-args-with-path ] [ 254 _exit ] recover
79 M: unix current-process-handle ( -- handle ) getpid ;
81 M: unix run-process* ( process -- pid )
82 [ spawn-process ] curry [ ] with-fork ;
84 M: unix kill-process* ( pid -- )
85 SIGTERM kill io-error ;
87 : find-process ( handle -- process )
88 processes get swap [ nip swap handle>> = ] curry
93 : code>status ( code -- obj )
94 dup WIFEXITED [ WEXITSTATUS ] [ WTERMSIG signal boa ] if ;
96 M: unix wait-for-processes ( -- ? )
97 0 <int> -1 over WNOHANG waitpid
102 [ swap *int code>status notify-exit f ] [ 2drop f ] if