如何在 Node JS 中杀死 exec child_process

问题描述 投票:0回答:1

我通过另一个node.js脚本(电子)启动node.js脚本(子进程)并尝试杀死子进程。我不明白,该怎么做,请帮忙

附注操作系统 - Windows 10

const { exec } = require('node:child_process');

function AppServer(code) {
    let child_proc;
    const exec_options = {
        killsignal: 'SIGTERM'
    }
    if (code == 1) {
        child_proc = exec('node "../server/index.js"', exec_options);
    } else if (code == 0) {
        child_proc.kill('SIGTERM');
}
}

javascript node.js electron
1个回答
0
投票

考虑到所涉及的具体挑战,以下是如何在 Windows 10 上的 Node JS 中有效终止 exec child_process:

  1. 将生成优先于执行:

虽然 exec 很方便,但 spawn 可以更好地控制子进程,包括终止。通常建议用于涉及终止子进程的场景。 2. 使用 detached: true 选项:

此选项将子进程与父进程分离,使其能够独立运行并更有效地终止。 3. 使用 process.kill() 和进程组 ID:

使用process.kill(-child_proc.pid)杀死整个进程组,确保所有关联的进程都被终止。 4. 处理潜在错误:

使用child_proc.killed或child_proc.exitCode检查子进程是否已经退出以避免错误。 5. 使用 SIGTERM 优雅终止(可选):

如果子进程可以处理信号,请先发送SIGTERM以允许其正常退出。如果它没有在合理的时间内终止,请使用 process.kill()。

const { spawn } = require('child_process');

函数AppServer(代码){ 让child_proc;

if (code == 1) {
    child_proc = spawn('node', ['../server/index.js'], { detached: true });
} else if (code == 0) {
    if (child_proc && (!child_proc.killed || child_proc.exitCode === null)) {
        try {
            child_proc.kill('SIGTERM'); // Attempt graceful termination
            setTimeout(() => {
                if (!child_proc.killed) {
                    process.kill(-child_proc.pid); // Forceful termination if SIGTERM fails
                }
            }, 2000); // Adjust timeout as needed
        } catch (error) {
            console.error("Error killing child process:", error);
        }
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.