简体   繁体   中英

Nodejs child process exit behavior

I have some strange (for me) behavior, that i do not understand. Please help.

Here a parent process test-parent.js :

const cp = require('child_process');
const path = require('path');

const fork = cp.fork(path.join(__dirname, 'test-child.js'));

fork.on('message', console.log);
fork.on('exit', (code) => {
  console.log('Exited with code:', code);
});

fork.send({ sum: 0, set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, - 1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11] });

and here a child (using a cpu-bound subset sum algorhythm) test-child.js :

const subsetSumFactory = require('./subset-sum');

process.on('message', (message) => {
  const subsetSum = subsetSumFactory(message.sum, message.set);

  subsetSum.on('match', (subset) => { });

  subsetSum.on('end', (totalSubsets) => {
    process.send({ event: 'end', data: { totalSubsets, pid: process.pid } });
  });

  subsetSum.start();
});

If i run parent code i got right message from child and child waits for another message.

So the point that i do not understand, is why child process does not exits immediately after run and waits for message from parent. Because if i run just child code: node test-child.js , it exits immediately.

UPDATE

Thanks all for answers.

Please explain one more thing. If i replace in child

process.on('message', ...) to process.once('message', ...)

then got response from child and then got Exited with code: 0

Why? I do not explicitly kill the child process...

So i decide to answer myself, because other answers did not fully clarify the situation.

Just testing some code and found out some interesting things. For example, if we have child process with some code:

process.send({message: 'foo'}) or simply console.log('foo')

It just exits immediately.

But there are some process events, on which if you have listener callback, it prevents child process from exit. For example process.on('message', ...) or process.on('disconnect', ...) .

And now the situation with process.once('message', ...) is clear. It just removes listener after it fired once. So now, without listener, nothing stops child process from exit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM