raz / site / content / advanced / 05-processes.txt

179 lines · 5.9 KiB · raw · history · last change 3fee2db6

1title: Time, randomness and other programs
2part: The library
3summary: Clocks, sleeping, random bytes, running a program with its output piped back, and signals.
4---
5Everything here is in `Sys`, and is the same procedures on every target raz supports: through system calls on Linux, through the C library elsewhere.
6
7## Clocks and sleeping
8
9`Sys.clock` is a clock that only goes forward, in nanoseconds: the one to measure a duration with. `Sys.now` is the wall clock, in nanoseconds since 1970 UTC, which can be set backwards, so it is for dates, not durations. `Sys.sleep` waits some milliseconds.
10
11```raz Timing run
12module Timing;
13import Out, Sys;
14
15proc main*;
16var t0, t1, elapsed: I64; wall: I64;
17begin
18 t0 := Sys.clock();
19 Sys.sleep(25);
20 t1 := Sys.clock();
21 elapsed := (t1 - t0) div 1000000; (* milliseconds *)
22 if (elapsed >= 25) and (elapsed < 1000) then
23 Out.str("slept about 25 ms\n");
24 end;
25 wall := Sys.now();
26 if wall > 1700000000000000000 then Out.str("after 2023\n"); end;
27end;
28
29end Timing.
30```
31
32Every duration is an `I64` of nanoseconds, because a 32-bit `INT` would hold only a couple of seconds of them. The library's rule is that what may overflow a small target's `INT` is an `I64`.
33
34## Random bytes
35
36`Sys.random` fills a slice with random bytes from the system. Anything else is made from that: a number in a range, a shuffle.
37
38```raz Dice run
39module Dice;
40import Out, Sys, Str;
41
42(* a number from 0 up to n, without bias *)
43proc below(n: INT): INT;
44var b: [8]U8; x, limit: U64;
45begin
46 limit := 0FFFFFFFFFFFFFFFFH - (0FFFFFFFFFFFFFFFFH mod U64(n)) - 1;
47 Sys.random(b);
48 x := Str.le(b);
49 while x > limit do
50 Sys.random(b);
51 x := Str.le(b);
52 end;
53 return INT(x mod U64(n));
54end;
55
56proc main*;
57var counts: [6]INT; i: INT; ok: BOOL;
58begin
59 for i := 1 to 6000 do INC(counts[below(6)]); end;
60 ok := true;
61 for i := 0 to 5 do
62 if (counts[i] < 800) or (counts[i] > 1200) then ok := false; end;
63 end;
64 if ok then Out.str("all six faces came up about a thousand times\n"); end;
65end;
66
67end Dice.
68```
69
70## Running a program
71
72`Sys.spawn` starts the program at a path with its arguments, environment, working directory and standard streams in a `Sys.Program` record. A zero field means this program's own. `Sys.wait` waits for it to end and says how: `exited` with its status, `killed` by a signal, or `stopped`.
73
74```raz Run run
75module Run;
76import Out, Sys;
77
78proc main*;
79var p: Sys.Program; pid, status: INT; how: Sys.Status;
80begin
81 p := {path: "/bin/echo", args: ["echo", "hello from a child"]};
82 pid := Sys.spawn(p);
83 if pid < 0 then Out.str("can't start\n"); return; end;
84 Out.flush; (* so that our text isn't behind the child's *)
85 _, how, status := Sys.wait(pid, true);
86 if how = Sys.exited then
87 Out.str("it exited with "); Out.int(status); Out.ln;
88 end;
89end;
90
91end Run.
92```
93
94## Capturing its output
95
96A program's standard output can be a pipe. `Sys.pipe` gives the descriptor to read and the one to write; give the write end to the child as `fds[1]`, close it here, and read until the end. This is how a program drives another: `ls`, a compiler, a script.
97
98```raz Capture run
99module Capture;
100import Out, Sys, Buf, Heap;
101
102proc main*;
103var
104 p: Sys.Program; pid, rd, wr, n, status: INT; how: Sys.Status;
105 chunk: [256]U8; b: Buf.Buf;
106begin
107 rd, wr := Sys.pipe();
108 p := {path: "/bin/sh", args: ["sh", "-c", "echo one; echo two; exit 7"]};
109 p.fds[1] := wr;
110 pid := Sys.spawn(p);
111 Sys.close(wr); (* only the child writes now *)
112 Buf.init(b, Heap.heap);
113 defer Buf.done(b);
114 n := Sys.read(rd, chunk);
115 while n > 0 do
116 Buf.str(b, chunk[0..n]);
117 n := Sys.read(rd, chunk);
118 end;
119 Sys.close(rd);
120 _, how, status := Sys.wait(pid, true);
121 Out.str("captured: "); Out.str(Buf.bytes(b));
122 Out.str("status "); Out.int(status); Out.ln;
123 if how = Sys.exited then Out.str("(a normal exit)\n"); end;
124end;
125
126end Capture.
127```
128
129Closing the write end in the parent matters: the read ends only when every holder of the write end has closed it.
130
131## Environment and working directory
132
133`Sys.env("HOME")` is an environment variable's value, or an empty string if it is unset. `Sys.workDir` and `Sys.setWorkDir` read and change the directory. The `Sys.Program` record's `env`, `onlyEnv` and `dir` give a child its own.
134
135```raz Where run
136module Where;
137import Out, Sys;
138
139proc main*;
140var p: Sys.Program; pid, rd, wr, n: INT; chunk: [64]U8;
141begin
142 if Sys.env("RAZ_SURELY_UNSET") = "" then Out.str("unset reads as empty\n"); end;
143 rd, wr := Sys.pipe();
144 p := {path: "/bin/sh", args: ["sh", "-c", "echo $GREETING from $(pwd)"],
145 env: ["GREETING=hello"], dir: "/tmp"};
146 p.fds[1] := wr;
147 pid := Sys.spawn(p);
148 Sys.close(wr);
149 n := Sys.read(rd, chunk);
150 Out.str(chunk[0..n]);
151 Sys.close(rd);
152 _, _, _ := Sys.wait(pid, true);
153end;
154
155end Where.
156```
157
158## Signals
159
160A signal, Ctrl-C's `sigInt` or `sigTerm` from `kill`, ends a program unless it says otherwise. `Sys.catch` takes signals away from what they would do and gives an fd that is ready to read when one comes, so a program that waits on fds anyway, with `Sys.readyOf`, waits for signals the same way; `Sys.caught` gives each in turn. `Sys.handle` is for a program that waits inside a system call, as a shell waits for its program: the signal is noted for `Sys.came`, and the call it comes during fails with -4 (EINTR) rather than going on. Nothing of the program runs when the signal comes; it looks after the call returns.
161
162```raz Signals run
163module Signals;
164import Out, Sys;
165
166proc main*;
167var fd: INT;
168begin
169 fd := Sys.catch([Sys.sigUsr1]);
170 _ := Sys.kill(Sys.pid(), Sys.sigUsr1);
171 if Sys.ready(fd, 1000) and (Sys.caught(fd) = Sys.sigUsr1) then Out.str("caught sigUsr1\n"); end;
172 _ := Sys.handle(Sys.sigUsr2);
173 _ := Sys.kill(Sys.pid(), Sys.sigUsr2);
174 if Sys.came(Sys.sigUsr2) then Out.str("sigUsr2 came\n"); end;
175 if not Sys.came(Sys.sigUsr2) then Out.str("and was seen once\n"); end;
176end;
177
178end Signals.
179```