8

以下代码:

#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [100],);

throw new Error("failure");

产生一个子进程并退出而不等待子进程退出。

我怎么能等呢?我想调用 waitpid(2) 但 child_process 似乎没有 waitpid(2)。

添加:

抱歉,我真正想要的是在父进程存在时杀死子进程,而不是等待它。

4

2 回答 2

13
#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [10]);

x.on('exit', function () {
    throw (new Error("failure"));
});

编辑:

您可以通过向主添加监听器来监听主进程,process例如process.on('exit', function () { x.kill() })

但是抛出这样的错误是一个问题,你最好关闭这个过程process.exit()

#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [100]);

process.on('exit', function () {
    x.kill();
});

process.exit(1);
于 2013-02-21T10:11:24.020 回答
3
#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [10]);

process.on('exit', function() {
  if (x) {
    x.kill();
  }
});
于 2013-02-21T10:26:37.293 回答