How to check if a process is ignoring or handling a signal?

Viewed 493

Using signal() or, preferably, sigaction(), we can choose to ignore or explicitly handle most of the POSIX signals. For example, in order to ignore SIGCHLD we could do the following:

struct sigaction sa_chld = { .sa_handler = SIG_IGN };
sigaction(SIGCHLD, &sa_chld, NULL);

Is there also a way to figure out if a given signal is being ignored and/or caught by the program?

Ideally, I'd like to distinguish if a signal...

  • is being handled as per the default actions
  • is being ignored explicitly
  • is being caught explicitly
2 Answers

For a running process, you can check out /proc/PID/status and check the fields SigBlk, SigIgn, and SigCgt for blocked, ignored, and caught signals respectively.

Someone wrote a utility script handy to "decode" it which I personally find very useful and been using it.

See proc documentation for details and more relevant fields.

Yes.

Example:

#include <signal.h>
#include <stdio.h>
void h(int Sig){(void)Sig; }
int main()
{
    signal(1,SIG_IGN); //note: setting ign/dfl is more compat (and still safe) with signal()
    sigaction(2, &(struct sigaction){.sa_handler=h},0);

    for(int i=1; i<8; i++){
        struct sigaction oldsa;
        sigaction(i, 0, &oldsa);
        if(!(oldsa.sa_flags&SA_SIGINFO)){
            if(oldsa.sa_handler==SIG_IGN) printf("%d ignored\n", i);
            else if(oldsa.sa_handler==SIG_DFL) printf("%d defaulted\n", i);
            else goto caught;
        }else caught:
            printf("%d caught\n", i);
    }

}

Example output:

1 ignored
2 caught
3 defaulted
4 defaulted
5 defaulted
6 defaulted
7 defaulted

Nonportably on Linux, you can also parse /proc/$PID/stat (or status, which has the human-readable version) to see if the signal is in the caught/ignored mask for the process (if(mask&(1ul<<(signalnumber-1)) printf("%d in the mask", signalnumber); ).

Linux maintains the list of caught/ignored signals as bitmasks, but POSIX doesn't expose those and instead requires you to obtain each individual disposition seperately vi a non-setting call to sigaction.

Related