Linux C: upon receiving a signal, is it possible to know the PID of the sender?

daisy picture daisy · Jul 16, 2012 · Viewed 9.8k times · Source

Suppose my C program handles SIGUSR1.

When it receives this signal, is it possible to know who sent it? I.e., How to get the pid of sender process?

Answer

duskwuff -inactive- picture duskwuff -inactive- · Jul 16, 2012

Yes, if you use the sigaction() call to set up your signal handler instead of signal. Doing so will let you set up a signal handler that takes three parameters:

  • An int, for the signal number (just like signal)
  • A siginfo_t *, which is a structure containing all sorts of information about the source of the signal, including the pid of the sender if applicable. (It also includes some information about the cause of the signal for automatic signals like SIGSEGV.)
  • A ucontext_t *, which has to do with which thread got the signal. Mostly ignorable.