简体   繁体   中英

Best way to know if SIGUSR1 was sent to a process

I am coding in c and wanted to know via coding what's the best way to know if a signal (for example SIGUSR1) terminated a process. Is there a way to make it with a function and flag it so other processes may know it?

More info: The process is a program I did in C. Later when the process ends (with the signal or not) I wanted another program I have to know it. They are connected via fifos.

In the parent process, you can use the wait() system call's WIFSIGNALED(status) macro to check if the child process was terminated by a signal.

Also you can get the signal number using WTERMSIG(status) macro.

Here's a code to demonstrate the idea.

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

int main()
{
    pid_t n = fork();
    if(n==0)
    {
        execvp(/*Some program here for child*/);
    }

    //parent does something

    //Parent waits for child to exit.
    int status;
    pid_t childpid = wait(&status);

    if(WIFSIGNALED(status))
        printf("Parent: My child was exited by the signal number %d\n",WTERMSIG(status));
    else
        printf("Parent: My child exited normally\n"):

    return 0;
}

You can read more about it in the manual: man 2 wait

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM