Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/posix-node/scratch/fork.js
1070 views
1
// node fork.js
2
3
const { dup2, execv, fork, waitpid, pipe } = require("..");
4
if (
5
// for typescript
6
dup2 == null ||
7
execv == null ||
8
fork == null ||
9
waitpid == null ||
10
pipe == null
11
) {
12
throw Error("bug");
13
}
14
const { closeSync, readSync, writeSync, fsyncSync } = require("fs");
15
16
//execv("/bin/ls", ["/bin/ls"]);
17
18
const stdin = pipe();
19
const stdout = pipe();
20
const stderr = pipe();
21
const pid = fork();
22
const HELLO = "hello";
23
24
if (pid == 0) {
25
// child
26
console.log("hi from child");
27
dup2(stdin.readfd, 0);
28
dup2(stdout.writefd, 1);
29
30
closeSync(stdin.writefd);
31
closeSync(stdin.readfd);
32
closeSync(stdout.writefd);
33
closeSync(stdout.readfd);
34
35
// connect up stdin and stdout
36
//execv("/bin/echo", ["/bin/echo", HELLO]);
37
console.log("doing execv");
38
39
// execv("/bin/cat", ["/bin/cat"]);
40
41
execv("/usr/bin/tr", [
42
"/usr/bin/tr",
43
"abcdefghijklmnopqrstuvwxyz",
44
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
45
]);
46
} else {
47
// parent
48
console.log("hi from parent, child=", pid);
49
//setTimeout(() => {
50
let b = Buffer.alloc(10000);
51
console.log("write to child");
52
writeSync(stdin.writefd, HELLO);
53
console.log("close stdin");
54
closeSync(stdin.writefd);
55
console.log("read output from the child...");
56
readSync(stdout.readfd, b);
57
const s = b.toString("utf8", 0, HELLO.length);
58
console.log("s = ", s);
59
console.log("waiting for child to end...");
60
console.log(waitpid(pid, 0));
61
// }, 1000);
62
}
63
64