我無法停止產生子進程的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 });
我聽stdout
和stderr
和close
:
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
子進程?
當它從終端上運行時退出,爲什麼會是這樣有必要嗎? NodeJS進程在TTY中的表現有何不同? – Aaron
我試過了。它確實允許'docker.js'進程退出(但是我的問題仍然是爲什麼當從CLI不需要時這是需要的),但是子碼頭docker-compose進程繼續運行。 – Aaron
我在碼頭以外遇到過這個問題。在Node.js中使用子進程時我認爲這裏的主要區別在於處理過程 - 如果子進程 - 處理一個是你的nodejs腳本,如果你從CLI啓動 - 這是一些操作系統進程。 – Lazyexpert