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

Viewed 12528

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?

4 Answers

Here's a complete example of the POSIX-standard sigaction() API:

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void sigusr1(int signo, siginfo_t *si, void *data) {
  (void)signo;
  (void)data;
  printf("Signal %d from pid %lu\n", (int)si->si_signo,
         (unsigned long)si->si_pid);
  exit(0);
}

int main(void) {
  struct sigaction sa;
  memset(&sa, 0, sizeof(sa));
  sa.sa_flags = SA_SIGINFO;
  sa.sa_sigaction = sigusr1;
  if (sigaction(SIGUSR1, &sa, 0) == -1) {
    fprintf(stderr, "%s: %s\n", "sigaction", strerror(errno));
  }
  printf("Pid %lu waiting for SIGUSR1\n", (unsigned long)getpid());
  for (;;) {
    sleep(10);
  }
  return 0;
}

Try to run it and then send it SIGUSR1 (e.g. kill -SIGUSR1 that-pid from a shell)

sigaction function: http://pubs.opengroup.org/onlinepubs/009604499/functions/sigaction.html

siginfo structure: http://pubs.opengroup.org/onlinepubs/009604499/basedefs/signal.h.html

Related