Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c/linux infinite loop application: deallocate memory if kill -9 command is called

I developed a C application in linux that contains an infinite loop while(1). There are some pointers that are dynamically allocated and are useful under the infinite loop, so the only time to deallocate memory is after interrupting the while(1) by ctrl-z, ctrl-c, kill -9 apppid, killall appname. So the idea is that I associate new handler that deallocates memory to the interruption events signals.

void deallocatehandler(int signal){ printf("Memory Deallocation\n"); exit(0);}

int main(){
    signal(SIGINT, &deallocatehandler);
    signal(SIGTSTP, &deallocatehandler);
    signal(SIGKILL, &deallocatehandler);

    while(1){
        /**
        Some code here
        **/
    }
}

If I press ctrl-c or ctrl-z the handler is called but the problem is with SIGKILL. The commands kill -9 and killall doesn't launch the handler.

Has someone an idea why? and is there suggestions to correct it?

like image 833
Kallel Omar Avatar asked Oct 24 '17 10:10

Kallel Omar


2 Answers

The whole point of SIGKILL is to kill the process no matter what. That's why you're not allowed to handle it.

In most cases, you start with a SIGTERM to give the process a chance to exit nicely. SIGKILL is usually used as a last resort when SIGTERM does not work. After all, the expected behavior from SIGTERM is that the process exits. If it doesn't you know that something is wrong.

From the manual

The SIGTERM signal is a generic signal used to cause program termination. Unlike SIGKILL, this signal can be blocked, handled, and ignored. It is the normal way to politely ask a program to terminate.

...

The SIGKILL signal is used to cause immediate program termination. It cannot be handled or ignored, and is therefore always fatal. It is also not possible to block this signal.

In the same document, you can also read this interesting thing

In fact, if SIGKILL fails to terminate a process, that by itself constitutes an operating system bug which you should report.

like image 164
klutt Avatar answered Oct 05 '22 03:10

klutt


You can't catch SIGKILL and SIGSTOP signals. So your signal handler wouldn't do anything. There's nothing you can do when your process receives SIGKILL, let alone any memory cleanup. On Linux, memory will be cleaned up on program exit, so this is probably not an issue. Usually such cleanup-on-exit is done for SIGTERM.

The correct answer is don't send SIGKILL (kill -9 should only be used if kill itself doesn't work). That's not the way to request to a process to terminate itself. Send SIGTERM first and if it doesn't work, then send SIGKILL.

like image 37
P.P Avatar answered Oct 05 '22 02:10

P.P