简体   繁体   English

如何在 windows 中正确杀死由 node.js/electron 生成的 child_process?

[英]How can I kill a child_process spwaned by node.js/electron correctly in windows?

I am using Electron, Python and Flask to develop an app in Windows.我正在使用 Electron、Python 和 Flask 在 ZAEA23489CE3AACDB43406EBB28E0Z 中开发应用程序。

I use我用

require('child_process').spawn('python', [_script,port]) 

to start a child_process, but I cannot kill this child_process correctly.启动一个child_process,但我无法正确终止这个child_process。

When the electron app was closed, there was still a process called 'python' working in the background.当 electron 应用程序关闭时,仍然有一个名为“python”的进程在后台工作。

I tried almost every way, for instance p.kill(), or using taskkill.我几乎尝试了所有方法,例如 p.kill(),或者使用 taskkill。

Here is the python code:这是 python 代码:

from flask import Flask
import logiccode as mine

app = Flask(__name__)

@app.route('/hello')
def hello_world():
   return mine.HelloWorld()


if __name__ == '__main__':
   app.run(debug = True)
//create
pyProc = require('child_process').spawn('python', [_script,port])
    if (pyProc != null) {
        console.log('child process success\n')
        console.log(pyProc.pid);
    }

//kill

if(process.platform=='win32'){
        require('child_process').spawn('taskkill',['/pid','/f','/t',pyProc.pid]);
    }else{
        pyProc.kill();
        pyProc = null
        pyPort = null
    }

If there is some error in the code, please tell me how I can kill this child_process correctly.如果代码中有一些错误,请告诉我如何正确杀死这个 child_process。

I don't see any reason for the Windows-specific branch there, I assume you added it when pyProc.kill() didn't work. 我在那里看不到Windows特定分支的任何原因,我假设您在pyProc.kill()无法正常工作时添加了它。

kill defaults to SIGTERM. kill默认为SIGTERM。 I'd expect that to work, but if you're seeing it not work, you can use the nuclear option of SIGKILL instead. 我希望它能起作用,但是如果您发现它不起作用,则可以改用SIGKILL的核选项。 As it says in signal(7) : 就像在signal(7)说的那样:

The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored. 无法捕获,阻止或忽略信号SIGKILL和SIGSTOP。

So: 所以:

//kill
pyProc.kill('SIGKILL');
pyProc = null
pyPort = null

Hope it is not too late but I ran into the same problem, the reason why flask cannot be killed is because debug mode is set to True.希望现在还不算太晚,但我遇到了同样的问题,无法杀死 flask 的原因是因为调试模式设置为 True。 Just call app.run() and node will kill flask.只需调用 app.run(),节点就会杀死 flask。

if __name__ == '__main__':
   app.run()

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

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