简体   繁体   English

如何真正杀死child_process nodejs

[英]How to REALLY kill a child_process nodejs

I'm using mocha with Nodejs to test my restApi. 我正在使用带有Nodejs的mocha来测试我的restApi。 When I run mocha, I tell my test to create a child_process and run the API so I can make requests to it. 当我运行mocha时,我告诉我的测试创建一个child_process并运行API,以便我可以向它发出请求。

The problem is whenever the test exits (finishing or crashing), it seems that the API keeps running on background. 问题是每当测试退出(完成或崩溃)时,似乎API在后台运行。 I've seen some answers here that instructs to manually kill the child process whenever the main process exits. 我在这里看到了一些答案,指示在主进程退出时手动终止子进程。 So I did it like this: 所以我这样做了:

export function startProcess(done) {
    const child = spawn('babel-node', ["app.js"]);

    child.stdout.on("data", function(data) {
        data = data.toString();
        // console.log(data.toString());

        if(data.indexOf("Server online") > -1) done();
    });

    child.stderr.on('data', function(err) {
        console.log("ERROR: ", err.toString());
    });

    child.on('exit', function(code) {
        console.log("PROPERLY EXITING");
        console.log("Child process exited with code", code);
    });

    process.on('exit', function(code) {
        console.log("Killing child process");
        child.kill();
        console.log("Main process exited with code", code);
    });
}

When the main process exits it does log "Killing child process", meaning that child.kill() was indeed called. 当主进程退出时,它会记录“Killing child process”,这意味着确实调用了child.kill() But if I try to run my test again, when the spawn command gets called, the API throws an error 但是如果我再次尝试运行我的测试,当调用spawn命令时,API会抛出错误

Error: listen EADDRINUSE :::3300 错误:听EADDRINUSE ::: 3300

, meaning that the API is still running and that port address is taken. ,意味着API仍在运行,并且采用了该端口地址。

So I have to run sudo pkill node to really kill all node process and then npm test works again. 所以我必须运行sudo pkill node来真正杀死所有节点进程,然后npm test再次运行。

Am I missing something? 我错过了什么吗? Is this really the way to achieve what I'm expecting? 这真的是实现我期待的方式吗?

I thought about using child_process.exec to run sudo pkill node on my process.on('exit') listener, but that doesnt seem like a smart thing to do. 我想过使用child_process.exec在我的process.on('exit')监听sudo pkill node上运行sudo pkill node ,但这看起来不是一件好事。

This is happening both in Mac and Ubuntu. Mac和Ubuntu都会发生这种情况。

Any suggestions? 有什么建议? Thanks 谢谢

"exit" is an event that gets triggered when node finishes it's event loop internally, it's not triggered when you terminate the process externally. “exit”是一个事件,当节点在内部完成它的事件循环时触发,当你从外部终止进程时它不会被触发。

What you're looking for is executing something on a SIGINT. 您正在寻找的是在SIGINT上执行某些操作。

Have a look at http://nodejs.org/api/process.html#process_signal_events 看看http://nodejs.org/api/process.html#process_signal_events

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM