Path: blob/main/core/posix-node/scratch/fork.js
1396 views
// node fork.js12const { dup2, execv, fork, waitpid, pipe } = require("..");3if (4// for typescript5dup2 == null ||6execv == null ||7fork == null ||8waitpid == null ||9pipe == null10) {11throw Error("bug");12}13const { closeSync, readSync, writeSync, fsyncSync } = require("fs");1415//execv("/bin/ls", ["/bin/ls"]);1617const stdin = pipe();18const stdout = pipe();19const stderr = pipe();20const pid = fork();21const HELLO = "hello";2223if (pid == 0) {24// child25console.log("hi from child");26dup2(stdin.readfd, 0);27dup2(stdout.writefd, 1);2829closeSync(stdin.writefd);30closeSync(stdin.readfd);31closeSync(stdout.writefd);32closeSync(stdout.readfd);3334// connect up stdin and stdout35//execv("/bin/echo", ["/bin/echo", HELLO]);36console.log("doing execv");3738// execv("/bin/cat", ["/bin/cat"]);3940execv("/usr/bin/tr", [41"/usr/bin/tr",42"abcdefghijklmnopqrstuvwxyz",43"ABCDEFGHIJKLMNOPQRSTUVWXYZ",44]);45} else {46// parent47console.log("hi from parent, child=", pid);48//setTimeout(() => {49let b = Buffer.alloc(10000);50console.log("write to child");51writeSync(stdin.writefd, HELLO);52console.log("close stdin");53closeSync(stdin.writefd);54console.log("read output from the child...");55readSync(stdout.readfd, b);56const s = b.toString("utf8", 0, HELLO.length);57console.log("s = ", s);58console.log("waiting for child to end...");59console.log(waitpid(pid, 0));60// }, 1000);61}626364