|
| 1 | +import { fork } from "node:child_process"; |
| 2 | + |
| 3 | +const child = fork(new URL("./worker.ts", import.meta.url), [], { |
| 4 | + stdio: ["ignore", "ignore", "inherit", "ipc"], |
| 5 | +}); |
| 6 | + |
| 7 | +// Start the deadline after the child is ready so process startup is not part |
| 8 | +// of the bound. Queued IPC must not wait for the idle poll timeout (1 second |
| 9 | +// per handoff), or for this timer to wake the loop. No periodic wakeups. |
| 10 | +let replies = 0; |
| 11 | +let sent = 0; |
| 12 | +let disconnected = false; |
| 13 | +child.once("message", () => { |
| 14 | + const deadline = setTimeout(() => { |
| 15 | + console.log("IPC stalled"); |
| 16 | + }, 500); |
| 17 | + child.on("message", (message: { value: number }) => { |
| 18 | + replies++; |
| 19 | + if (message.value < 3) { |
| 20 | + child.send({ value: message.value + 1 }, (error) => { |
| 21 | + if (error) throw error; |
| 22 | + sent++; |
| 23 | + }); |
| 24 | + } |
| 25 | + }); |
| 26 | + child.once("disconnect", () => { |
| 27 | + disconnected = true; |
| 28 | + clearTimeout(deadline); |
| 29 | + }); |
| 30 | + child.send({ value: 1 }, (error) => { |
| 31 | + if (error) throw error; |
| 32 | + sent++; |
| 33 | + }); |
| 34 | +}); |
| 35 | +child.once("exit", (code) => { |
| 36 | + console.log("replies", replies, "sent", sent, "disconnected", disconnected, "exit", code); |
| 37 | +}); |
0 commit comments