2017-07-14 261 views
0

我无法停止产生子进程的node.js进程。如果我从终端运行.js进程,我可以使用Ctrl+C来停止它。但是如果我从NodeJS应用产生它,我不能用kill("SIGINT")来杀死它 - 它只是继续并继续报告stdout杀死产生进程的进程

这是设置。我有一个脚本,让我们把它叫做docker.js和它这样做:

// docker.js 
child_process.spawn("docker-compose", ["up", "-d", ...args], { stdio: 'inherit' }); 

docker-compose up command做了很多的东西,而且几分钟运行一段时间,有时。

如果我从终端运行./docker.js,我可以在任何时候按下Ctrl+C一致地突破。

如果我产卵docker.js从内不同的NodeJS应用程序(在我的情况的电子应用程序),使用spawn()fork()

// DockerApp.js 

const dir = `path/to/dockerjs/file/`; 

// Tried this with and without `detached: true` 
const child = spawn("node", [`./docker.js`, ...args], { cwd: dir, env, detached: true }); 

// Also tried this, which uses Electron's packaged node process 
const child = fork(`./docker.js`, args, { cwd: dir, env, silent: true }); 

我听stdoutstderrclose

child.stdout.on("data", data => { 
    console.log(`stdout: ${data}`); 
}); 

child.stderr.on("data", data => { 
    console.log(`stderr: ${data}`); 
}); 

child.on("close", code => { 
    console.log(`child process exited with code ${code}`); 
}); 

一切工作正常(我看到预期的输出,并最终“关闭”完成后),但如果我尝试完成前停止该过程是这样的:

child.kill("SIGINT"); // Equivalent to Ctrl+C in terminal 

子进程只是继续运行,我不断收到docker-compose输出通过stdout

我试过了一段时间,但我不知道如何从NodeJS/Electron应用程序产生子进程时停止docker.js。我认为Ctrl+C从终端和child.kill("SIGINT")会有相同的行为,但它不。

任何人都可以解释这里发生了什么?我该如何可靠地从我的NodeJS应用程序中清除这个docker.js子进程?

回答

0

尝试这样的事情在孩子的过程:

process.on('SIGINT',() => { 
    console.log('Received SIGINT'); 
    process.exit(0); 
}); 
+0

当它从终端上运行时退出,为什么会是这样有必要吗? NodeJS进程在TTY中的表现有何不同? – Aaron

+0

我试过了。它确实允许'docker.js'进程退出(但是我的问题仍然是为什么当从CLI不需要时这是需要的),但是子码头docker-compose进程继续运行。 – Aaron

+0

我在码头以外遇到过这个问题。在Node.js中使用子进程时我认为这里的主要区别在于处理过程 - 如果子进程 - 处理一个是你的nodejs脚本,如果你从CLI启动 - 这是一些操作系统进程。 – Lazyexpert