C program to print the PID of the sender process that sends signal to receiver process

/************************************************* C program to print the PID of the sender process which

 sends signal to receiver process *************************************************/

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

static struct sigaction siga;

static void signal_hanlder(int sig, siginfo_t *siginfo, void *context) {
    /* get pid of sender process */
    pid_t sender_pid = siginfo->si_pid;

    if(sig == SIGTERM) {
        printf("received SIGTERM. Sender process PID: %d\n", sender_pid);
        exit(0);
    }

    return;
}

int main_loop() {
    /* print pid */
    printf("process [%d] started.\n", (int)getpid());

    /* prepare sigaction */
    siga.sa_sigaction = *signal_hanlder;
    siga.sa_flags |= SA_SIGINFO; // get detail info

    /* change signal action */
    if(sigaction(SIGTERM, &siga, NULL) != 0) {
        printf("error sigaction()");
        return errno;
    }

    /* Enter into infinite loop here. */
    while(1);

    return 0;
}

int main(int argc, char *argv[]) {
    main_loop();

    return 0;
}

Output


Neelkanth_221$ gcc test123.c
Neelkanth_221$ ./a.out &
[1] 3316

Neelkanth_221$ process [3316] started.   --> pid of the current process

Neelkanth_221$
Neelkanth_221$
Neelkanth_221$ ps -elf | grep a.out
0 R labuser   3316  2868 84  80   0 -  1053 -      22:57 pts/33   00:00:02 ./a.out
0 S labuser   3318  2868  0  80   0 -  3989 pipe_w 22:57 pts/33   00:00:00 grep --color=auto a.out


Neelkanth_221$ kill -15 3316        --> from bash shell, send SIGTERM to current process.
Neelkanth_221$ received SIGTERM. Sender process PID: 2868   --> pid of the process sending signal to current process

[1]+  Done                    ./a.out
Neelkanth_221$
Neelkanth_221$ ps -elf | grep 2868
0 S labuser   2868  2867  0  80   0 -  6824 wait   19:59 pts/33   00:00:00 -bash
0 R labuser   3319  2868  0  80   0 -  5664 -      22:57 pts/33   00:00:00 ps -elf
0 S labuser   3320  2868  0  80   0 -  3989 pipe_w 22:57 pts/33   00:00:00 grep --color=auto 2868