jtlapp / node-cleanup

installs custom cleanup handlers that run on exiting node
MIT License
164 stars 10 forks source link

Killing process on windows #8

Open josezulu opened 7 years ago

josezulu commented 7 years ago

Killing the node process with ctrl-c triggers the cleanup fine (Windows 7 by the way). But when I kill it via Task Manager, or it gets killed by rebooting the PC, it doesn't seem to trigger.

This is my code:

function log(message)
{
    // log to the logfile
    fs.appendFileSync(logFile, timestamp() + message + "\n", "utf8");

    console.log(message);
}

nodeCleanup(function(exitCode, signal)
{
    log("Watcher ended: exitCode: \'" + exitCode + "\', signal: \'" + signal + "\'.");
});

Maybe I'm doing something wrong?

jtlapp commented 7 years ago

It's great to get confirmation that things seem to be working on Windows. I don't use Windows, but from what I'm reading, you're seeing expected behavior.

Windows isn't POSIX and doesn't actually support signals at all. They're emulated. Apparently node.js doesn't provide emulation for SIGTERM, which allows for gracefully exiting. However, there are apparently programs for issuing SIGTERM to Windows processes.

Neither POSIX OSs nor Windows can intercept SIGKILL, so whatever Windows actions are equivalent to SIGKILL wouldn't be intercepted anyway.

The above link offers a good explanation. There's also some information at this node.js page, but you have to scroll down to "Signal Events" because it's now in an iframe.

I can't say that the behavior you're seeing is the best we can do, but it appears to be the expected behavior.

jtlapp commented 7 years ago

Maybe there's another event we could intercept that would be helpful on Windows?

jtlapp commented 7 years ago

This note is pretty comprehensive, found on the page describing node.js processes:

Note: Windows does not support sending signals, but Node.js offers some emulation with process.kill(), and ChildProcess.kill(). Sending signal 0 can be used to test for the existence of a process. Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional termination of the target process.

josezulu commented 7 years ago

Thank you, jtlap, for your feedback. I'll have a look at the documentation you mention in your responses here above.

In the meantime, I deployed my script on a Windows 7 Professional machine. I wrapped it in a batch and launch/monitor it via Task Scheduler. The node process watches for file changes and executes child processes, so it's usually running. When I "end" the Task via Task Scheduler, the node process closes, and your module detects the "SIGHUP" message, so my log looks like this:

2017-05-03 13:14:05.367: Watcher Ended: exitCode: 'null', signal: 'SIGHUP'.

That works nicely! I haven't experimented with other "end" scenarios as of yet, but I wanted to report that this one is also detected :+1: