How do I know if a child Node.js process was from fork () or not?
I have a small application that can be forked or directly by a developer, and I would like to configure it slightly differently depending on how it was launched.
I know I can always pass arguments to signal that it was a fork, but I was just curious if there was a way to tell if I could somehow find out in the child process if it came from fork()
, I looked around in process
but nothing not found.
source to share
This is a bit of a hack, but you can check if it exists process.send
in your application. When it was started using fork()
, it will exist.
if (process.send === undefined) {
console.log('started directly');
} else {
console.log('started from fork()');
}
Personally, I would probably set an environment variable in the parent and check this in the child:
// parent.js
child_process.fork('./child', { env : { FORK : 1 } });
// child.js
if (process.env.FORK) {
console.log('started from fork()');
}
source to share