[英]How to clean child processes on child_process.spawn() in node.js
The following code: 以下代码:
#!/usr/bin/env node
"use strict";
var child_process = require('child_process');
var x = child_process.spawn('sleep', [100],);
throw new Error("failure");
spawns a child process and exits without waiting the child process exiting. 生成子进程并退出而不等待子进程退出。
How can I wait it? 我该怎么办? I'd like to call waitpid(2) but child_process seems to have no waitpid(2).
我想调用waitpid(2)但是child_process似乎没有waitpid(2)。
ADDED: 添加:
Sorry, what I really want is to kill the child process when the parent exists, instead of wait it. 对不起,我真正想要的是在父项存在时终止子进程,而不是等待它。
#!/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"));
});
EDIT: 编辑:
You can listen for the main process by adding a listener to the main process
like process.on('exit', function () { x.kill() })
你可以通过向主进程添加一个监听器来监听主
process
如process.on('exit', function () { x.kill() })
But throwing an error like this is a problem, you better close the process by process.exit()
但抛出这样的错误是一个问题,你最好通过
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);
#!/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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.