I'm not fully understand why I can't kill a detached process. Can someone help me out?
Server (child process)
const server = spawn(
'npm',
[
'run',
'watch:be',
],
{
detached: true,
},
);
Await for the server to up and running
await waitOn({
resources: [
`https://localhost:${process.env.SERVER_PORT}`,
],
delay: 1000,
timeout: 30000,
});
console.log('server is up and running');
Wait a couple more seconds
await new Promise((resolve, reject): void => {
setTimeout((): void => {
resolve();
}, 2000);
});
console.log('Run test');
Kill the child server
server.kill();
console.log('Shutdown server');
All of these are in the same file.
The child process opened a new terminal window (when it does spawn
, which is expected), but doesn't close when kill
. Can someone point out what I have done wrong?
server.kill();
As per the node.js documentation, The subprocess.kill()
method sends a signal to the child process. When you use the detached
option, the node creates a separate process group for the child process and it is not part of the same process anymore.
detached <boolean>: Prepare child to run independently of its parent process
That is the reason kill
is not appropriate to use when detached
is used.
This has been discussed here: https://github.com/nodejs/node/issues/2098
As suggested in the above link, you should use process.kill
to kill the process ( https://nodejs.org/api/process.html#process_process_kill_pid_signal ). This should probably work for you:
process.kill(-server.pid)
You said that "The child process opened a new terminal window..."
Based on this behaviour, it seems that your OS is Windows.
On Windows, setting
options.detached
totrue
makes it possible for the child process to continue running after the parent exits. The child will have its own console window. Once enabled for a child process, it cannot be disabled.
For process.kill
, the second arg is the signal you want to send. By default, this signal is SIGTERM
. However, SIGTERM
doesn't seem to be supported on Windows, according to the Signal Events section of the Node.js docs.
'SIGTERM'
is not supported on Windows, it can be listened on.
Maybe try
process.kill(server.pid, 'SIGHUP')
or
process.kill(server.pid, 'SIGINT')
(This works on macOS but I've not tried it on Windows.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.