如何为子进程生成孙进程? [英] How to spawn a grandchild process for a child process?

查看:409
本文介绍了如何为子进程生成孙进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成了一个子进程,下面是代码:

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

使用选项 detached:true ,它将

我的问题是:如何在此子进程下运行孙子进程?因为在我的senario中,在生成此子进程之后,父进程将被杀死。因此,除了使用现有的子进程生成孙进程之外,我无法生成其他进程。

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.

推荐答案

首先,请注意,分离选项仅在双亲在Windows系统上死亡后才能使子存活。在Unix系统中,默认情况下,子级将保持活动状态。

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.

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

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();

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

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();

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

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

var fs = require('fs');

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

创建这些文件,将它们放在同一目录中,运行 node app。 js ,然后您应该看到 bob.txt 出现在同一目录中。如果您有任何问题,请告诉我。我想问的是,您是否知道 process.argv [0] 给您带来了什么,以及为什么要使用该参数生成新的子进程。

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.

这篇关于如何为子进程生成孙进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆