0

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.

  • Possible dupe of http://stackoverflow.com/questions/7696925/send-signal-to-process – Dellowar Dec 27 '16 at 15:46
  • okay, I asked it wrongly. Already fixed it – David Coelho Dec 27 '16 at 15:58
  • `SIGUSR1` doesn't necessarily terminate the process, so you may _catch_ this signal, write into a file some message indicating that this signal has been received and then shut down the program. – ForceBru Dec 27 '16 at 16:04
  • You need to elaborate more. What is your purpose? Is this process implemented by you or do you ask about any running process? Why do you need to know if some particular signal terminated the process? Please update your question with more information. – zoska Dec 27 '16 at 16:10
  • Already gave more info. Thanks. – David Coelho Dec 27 '16 at 16:19

1 Answers1

1

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

Raman
  • 2,735
  • 1
  • 26
  • 46
  • The problem is that the other process is connected via fifo. It isn't it's child. – David Coelho Dec 27 '16 at 16:23
  • @David Coelho Then there is no predefined way. You have to develop some mechanism yourself. For example: You can then catch the SIGUSR1 signal. Send a signal to the other process first before exiting the 1st process. The 2nd process also catches the signal and knows 1st process has exited. – Raman Dec 27 '16 at 16:25
  • I see. I will give it a try. Thanks for the support :) – David Coelho Dec 27 '16 at 16:26