简体   繁体   中英

Node child process can not run detached

I'm trying to fork a node child process with

child_process.fork("child.js")

and have it say alive after the parent exits. I've tried using the detached option like so:

child_process.fork("child.js", [], {detached:true});

Which works when using spawn, but when detached is true using fork it just fails silently, not even executing the child.js.

I've also tried

var p = child_process.fork("child.js")
p.disconnect(); 
p.unref();

But child still dies when the parent does. Any help or insight would be greatly appreciated.

EDIT:

Node Version: v5.3.0 Platform: Windows 8.1 Code:

//Parent
var child_process = require("child_process");

var p;
try{
  console.log(1)
  p = child_process.fork("./child.js")
  console.log(2)
} catch(e){
  console.log(e)
}
p.on('error', console.log.bind(console))

p.disconnect();
p.unref();

//To keep process alive
setTimeout(() => {
  console.log(1);
}, 100000);

--

//Child
var fs = require("fs");

console.log(3);

fs.writeFileSync("test.txt", new Date().toString());

setTimeout(()=>{
  console.log(1);
}, 100000);

I'm assuming you're executing your parent file from the command line, which is probably why it "appears" that the forked child is not executing. In reality when the parent process exits, the terminal stops waiting and thus prints a new line, waiting for your next command. This makes it seem like the child isn't executing, but trust me it is. Also there is no "detached" option for child_process.fork

Add some console.log() statements to your child process and you should see input printing in your terminal even after the parent has exited. If you don't it's because your child is prematurely exiting due to an error. Run your child process directly to debug it, before calling it from the parent.

Check out this quick example:

在此处输入图片说明

Hope this helps.

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