Gleno
Gleno

Reputation: 16969

XCode graceful program shutdown

I'm working on a server-like program in xcode, and I want it to shut down gracefully between debug runs. Basically the following line is not working

std::signal(SIGKILL, [](int){
    printf("got sigkill here!\n"); 
    //shut-down code here
});

I've tried trapping other signals, but so far SIGINT, SIGTERM and SIGABRT have not worked. How is xcode terminating the program, if it prints

Program ended with exit code: 9

to the console?

EDIT Apparently SIGKILL can not be caught, see this wikipedia entry.

In contrast to SIGTERM and SIGINT, this signal cannot be caught or ignored, and the receiving process cannot perform any clean-up upon receiving this signal

Upvotes: 1

Views: 6352

Answers (1)

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21223

You can't catch SIGKILL. When a process receives SIGKILL, it immediately terminates. This is used to kill buggy processes that won't respond or ignore the regular SIGINT. If you could catch SIGKILL, and possibly ignore it, then there would be no way to kill a buggy process apart from rebooting the machine.

Also, note that you're calling printf() in a signal handler, which is not allowed. You can't expect this to work.

You can have a look at signal-safe functions in signal manpage: http://man7.org/linux/man-pages/man7/signal.7.html - printf is not part of it, so all bets are off.

From the manpage:

A signal handler function must be very careful, since processing elsewhere may be interrupted at some arbitrary point in the execution of the program. POSIX has the concept of "safe function". If a signal interrupts the execution of an unsafe function, and handler calls an unsafe function, then the behavior of the program is undefined.

See this question for safe alternatives: Print int from signal handler using write or async-safe functions

Upvotes: 3

Related Questions