MOHAMED
MOHAMED

Reputation: 43598

How to detect kill of my process?

I want to detect the kill signal of my program inorder to execute some C instruction before leaving my program. my program is running on linux

Is it possible to do that? If yes how I can do it?

Upvotes: 0

Views: 2681

Answers (3)

David Ranieri
David Ranieri

Reputation: 41045

No, SIGKILL can not be handled, maybe you want to catch CTRL+C, then:

#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t stop;

void
inthand(int signum)
{
    stop = 1;
}

int
main(int argc, char **argv)
{
    signal(SIGINT, inthand);

    while (!stop)
        printf("a");

    printf("exiting safely\n");

    return 0;
}

Will do the trick

Upvotes: 1

Raghuram
Raghuram

Reputation: 3967

If SIGKILL or SIGTERM is sent to your process you cannot mask or ignore the signal. Other signals you can handle and mask it.

Upvotes: -1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272762

You can register a signal handler using sigaction(). Note that you cannot handle SIGKILL or SIGSTOP though.

Upvotes: 6

Related Questions