Skip to content

Commit 12934bb

Browse files
committed
Added example files
1 parent 0b660e6 commit 12934bb

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

child-processes/fork-child.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const fibonacci = (num) => num <= 1 ? 1 : fibonacci(num - 1) + fibonacci(num - 2)
2+
3+
process.on('message', ({n}) => {
4+
process.send({ fib: fibonacci(n), n })
5+
// optional - there is no reason why this child process
6+
// can't be called multiple times.
7+
process.exit()
8+
})

child-processes/fork-parent.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const { fork } = require('child_process')
2+
3+
const child1 = fork('fork-child')
4+
const child2 = fork('fork-child')
5+
const child3 = fork('fork-child')
6+
7+
// send data to the child process to perform the calculation
8+
child1.send({ n: 5 });
9+
child2.send({ n: 10 });
10+
child3.send({ n: 45 });
11+
12+
child1.on('message', (m) => {
13+
console.log('PARENT child1 got message:', m);
14+
});
15+
child2.on('message', (m) => {
16+
console.log('PARENT child2 got message:', m);
17+
});
18+
child3.on('message', (m) => {
19+
console.log('PARENT child3 got message:', m);
20+
});
21+
22+
child1.on('exit', () => {
23+
console.log('child1 exited');
24+
});
25+
child2.on('exit', () => {
26+
console.log('child2 exited');
27+
});
28+
child3.on('exit', () => {
29+
console.log('child3 exited');
30+
});

child-processes/index.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,6 @@ process.on('message', ({ n }) => {
130130
The parent process creates 3 child processes, and passes a range of numbers to them for calculating.
131131

132132
```javascript
133-
134133
const { fork } = require('child_process')
135134

136135
const child1 = fork('fork-child')

0 commit comments

Comments
 (0)