简体   繁体   中英

How to tell if child Node.js Process was from fork() or not?

I have a small application that could be executed by a fork or directly by a developer, and I would for it to get configured slightly differently depending on how it was started.

I know that I could always pass in arguments to to signal that it was a fork, but I was just curious if there was a way to tell if I could somehow know in the child process if it came from a fork() . I looked around in process but didn't find anything telling.

It's a bit of a hack, but you can check if process.send exists 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 for that in the child:

// parent.js
child_process.fork('./child', { env : { FORK : 1 } });

// child.js
if (process.env.FORK) {
  console.log('started from fork()');
}

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