How to spawn a grandchild process for a child process?

和自甴很熟 提交于 2019-12-13 07:37:23

问题


I have spawned a child process, below is the code:

const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr'], { detached: true });

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
  fs.writeFileSync('path-to-test.txt', 'stdout');
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
  fs.writeFileSync('path-to-test.txt', 'stderr');
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

With option detached: true, it will keep the child process running even the parent process is killed.

My question is: how to run a grandchild process under this child process? Because in my senario, after spawn this child process, the parent process will be killed. So I can't spawn another process, except using existing child process to spawn a grandchild process.


回答1:


First, it's important to note that the detached option only keeps the child alive after the parent dies on a Windows system. In Unix systems, the child will stay alive by default.

In order to spawn a "grandchild process", child_program.js would have to spawn a child process as well. Try this example out to see. Suppose you have app.js which contains the following:

const spawn = require('child_process').spawn;

const child = spawn(process.argv[0], [__dirname + '/child_program.js'], {
 detached: true,
 stdio: 'ignore'
});

child.unref();

And then suppose, child_program.js contains the following:

const spawn = require('child_process').spawn;

const child = spawn(process.argv[0], [__dirname + '/grandchild_program.js'], {
 detached: true,
 stdio: 'ignore'
});

child.unref();

And lastly, let's say grandchild_program.js does this:

var fs = require('fs');

fs.writeFileSync(__dirname + '/bob.txt', 'bob was here', 'utf-8');

Create these files, put them in the same directory, run node app.js and then you should see bob.txt show up in that same directory. Let me know if you have any questions. My question to you would be if you know what process.argv[0] gives you and why you're spawning new child processes with that argument.



来源:https://stackoverflow.com/questions/39502355/how-to-spawn-a-grandchild-process-for-a-child-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!