1

I am trying to catch SIGINT (CTRL + C). I want that when user type CTRL + C it will kill child process but the father process will continue normally. when I have child process in my program it works ok, but when I have not child process, I get "segmentation fault".

I have done this:

void sig_handler(int signo);
//========================================
int main()
{
    // CTRL + C => SIGINT handler
    struct sigaction act;
    act.sa_handler = sig_handler;
    sigfillset(&act.sa_mask);
    act.sa_flags = 0;

    // Catch the signal
    sigaction(SIGINT, &act, NULL);
...
// done some checks and then fork a child.
} 

// SIGINT handler
void sig_handler(int signo)
{
 // dont know what to write here
}
2
  • before forking your child process get the current process ID, then fork it your child and get its process ID also then when handling the signal check whether ctrl c is for the parent process ID or not then implement your logic according to it.
    – FZE
    Mar 27, 2016 at 0:22
  • On what line of code do you get the segmentation fault? Mar 27, 2016 at 14:18

1 Answer 1

1

I believe that just by using the sigset() you can achieve your goal.

I would quote some information from man page of sigset.

The sigset() function modifies signal dispositions. The sig argument specifies the signal, which may be any signal except SIGKILL and SIGSTOP. The disp argument specifies the signal's disposition, which may be SIG_DFL, SIG_IGN, or the address of a signal handler. If sigset() is used, and disp is the address of a signal handler, the system adds sig to the signal mask of the calling process before executing the signal handler; when the signal handler returns, the system restores the signal mask of the calling process to its state prior to the delivery of the signal. In addition, if sigset() is used, and disp is equal to SIG_HOLD, sig is added to the signal mask of the calling process and sig 's disposition remains unchanged. If sigset() is used, and disp is not equal to SIG_HOLD, sig is removed from the signal mask of the calling process.

Refer this link: sighold, sigignore, sigpause, sigrelse, sigset — legacy interface for signal management

You can establish a handler function that will be invoked when you get SIGINT.

void handler(int signo){
    // Here you can kill the child, if it exists
}

int main(int argc, char *argv[])
{
     ...
     sigset(SIGINT, handler);
     ...
}

Hope it helps you, if you need more help, just mention it in the comments.

1
  • Please upvote, if the answer solves your problem. --Thanks Jul 20, 2016 at 1:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.