0

My application starts a process and I need it to automatically close when the application closes. The application can be closed by the Task Manager, Ctrl + C or some other standard close operation.

I've tried using:

  • signal(SIGTERM, callback) from signal.h
  • SetConsoleCtrlHandler(callback, TRUE) from windows.h
  • atexit(callback) from stdlib.h

But none of them did the job.

Using signal

#include <iostream>
#include <csignal>
void onExit(int sig) {
    std::cout << "sig(" << sig << ")" << std::endl;
}
int main() {
    signal(SIGINT, onExit);
    int n;
    std::cin >> n;
}

Using SetConsoleCtrlHandler

I've copied the code from MSDN

Using atexit

#include <stdlib.h>
void onExit(void) {
    std::cout << "sig(" << ")" << std::endl;
}
int main() {
    atexit(onExit);
    int n;
    std::cin >> n;
}

None of the above solution called the callback when I terminated the application from the Task Manager nor the close button.

What should I do?

Ron
  • 14,674
  • 4
  • 34
  • 47
Ido Sorozon
  • 272
  • 1
  • 12
  • Programs with a "main" don't have a close button - they are console applications. – Martin Bonner supports Monica Jan 07 '19 at 17:15
  • I was talking about `cmd.exe` 'close' button – Ido Sorozon Jan 07 '19 at 18:49
  • 1
    No code in your application will run when you terminate it from Task Manager using "End Process" -- that calls `TerminateProcess` and the target process immediately stops running code. For the close 'X' and Task Manager End Task, `SetConsoleCtrlHandler` does work. But you need more than just a link to an MSDN example to help us help you. – Ben Voigt Jan 07 '19 at 21:23
  • @BenVoigt, console clients other than the effective owner can only be killed gracefully by killing the owner. In this case, each process has up to 5 seconds to handle the close event before the session server (csrss.exe) terminates it. In particular, gracefully killing a process by sending `WM_CLOSE` to its console window requires associating the window back to the process ID. The console selects one client thread/process as the effective owner of the window, which is stored as window data to special case `GetWindowThreadProcessId`. This is initially the process that allocates the console. – Eryk Sun Jan 08 '19 at 01:35

0 Answers0