Search code examples
javascriptnode.jspowershellbatch-filechild-process

how do I kill a node.js process from another node.js process?


I'm trying to run scripts/node.js processes from another node.js processes. I figured out how to start them with child_process.spawn() and I have the PID from it but i can't figure out how to kill them. Using child_process.exec() to run taskkill with doesn't work even with/F, even though it says the "task-killing" was successful, the node.js window is stil running. I've even tried powershell's stop-process but that doesn't work either. How do I kill it? (from node.js)

Edit:

Both process.kill(pid,15) and process.kill(pid,9) end with:

Error: kill ESRCH errno: -4040,code: 'ESRCH',syscall: 'kill'


Solution

  • NodeJS has a method called kill in the global process object, kill takes a PID (process id) and an optional SIGNAL (kill signal) to send to the process identified by PID.

    This is how to use it

    process.kill(pid, SIGNAL) -> SIGNAL is optional.

    Assuming the process id is 1000

    process.kill(1000), not specifying a signal automatically sends SIGTERM to process id 1000.

    It should be noted that SIGNAL can also be a number, the number value for SIGTERM is 15. SIGNAL NUMBERS

    For example, you can do this.

    process.kill(1000, 15) or process.kill(1000, 'SIGTERM') -> sends a terminate signal to process id 1000

    process.kill(1000, 9) or process.kill(1000, 'SIGKILL') -> sends a kill signal to process id 1000

    Documentation on process.kill.

    When pid does not exists, the nodejs process will throw ESRCH.