如何为子进程生成孙子进程?

时间:2016-09-15 02:36:02

标签: node.js child-process

我已经产生了一个子进程,下面是代码:

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}`);
});

使用选项detached: true,即使父进程被终止,它也会使子进程保持运行。

我的问题是:如何在这个子进程下运行孙子进程?因为在我的senario中,在生成这个子进程之后,父进程将被终止。所以我不能生成另一个进程,除了使用现有的子进程来生成一个孙进程。

1 个答案:

答案 0 :(得分:0)

首先,重要的是要注意,分离选项仅在父系统在Windows系统上死亡后才使子项保持活动状态。在Unix系统中,默认情况下,孩子将保持活着状态。

为了产生“孙子进程”,child_program.js也必须产生子进程。试试看这个例子吧。假设您有app.js,其中包含以下内容:

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

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

child.unref();

然后假设,child_program.js包含以下内容:

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

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

child.unref();

最后,让我们说grandchild_program.js这样做:

var fs = require('fs');

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

创建这些文件,将它们放在同一目录中,运行node app.js,然后您应该看到bob.txt显示在同一目录中。如果您有任何疑问,请告诉我。我的问题是,如果你知道process.argv[0]给你什么,以及为什么你用这个论点产生新的子进程。