2

In a command prompt window, I have a running process. While the process is still executing, I click the (red) 'X' in the corner of the command prompt window. The command prompt window closes, and the running process is terminated.

On Linux, closing the parent terminal of a running process will send that process SIGHUP. How do I catch this event on Windows?

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

3 Answers3

5

The equivalent of SIGHUP is provided through the callback you register with SetConsoleCtrlHandler. Your callback function will be called on an arbitrary threadpool thread with dwCtrlType = CTRL_CLOSE_EVENT. You've got 5 seconds to clean-up, you cannot cancel the close.

Sample code is available in this MSDN article

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

This cannot be done directly from command prompt. You would need a secondary anything (vbs, powershell or custom MyApp.exe) to catch cmd.exe when it is closed and react accordingly.

For instance, a VBS WMI monitor.

strComputer = "."
Set objSWbemServices = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!" & "\\" & strComputer & "\root\cimv2")
Set objEventSource = objSWbemServices.ExecNotificationQuery( "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'cmd.exe'")
Set objEventObject = objEventSource.NextEvent()
Wscript.Echo "CMD.exe closed"
Knuckle-Dragger
  • 6,644
  • 4
  • 26
  • 41
  • Though I would prefer a more laser focused monitor to track the exact PID of cmd.exe so that we don't accidentally trigger on a different cmd.exe instance. Still you get the idea. – Knuckle-Dragger Dec 13 '13 at 13:27
  • Also, this would not determine if Red X or if the batch simply finished, additional logic would need to be added to the end of the batch script to cancel the WMI monitor before batch ends so that it doesn't trigger upon normal completion. – Knuckle-Dragger Dec 13 '13 at 13:29
  • From an actual programming language you can use a console control handler and trap on console close event. – Knuckle-Dragger Dec 13 '13 at 13:43
  • see Hans post for more details of ConsoleCtrlHandler. – Knuckle-Dragger Dec 13 '13 at 17:07
0

"SIGHUP"... tested on Windows 8.1 pro + Node.js 0.10.24 works fine..

process.on('SIGHUP', function(){
    //Your code goes here.
});