简体   繁体   中英

Keeping parent process alive while child process will be terminated by SIGINT signal

As I dig deep into SIGNAL in c, I was wondering is it possible to keep parent process alive upon receiving SIGINT signal but I got a bit confused researching online as they isn't much discussion about it.

Is it possible to use signal handler to keep parent process alive by ignoring the SIGINT signal for parent process.

If yes, how should I implement it?

I would say, that there is nothing to discuss.

Have a look at the man page of signal(7) . In the section Standard signals , the default action for SIGINT is program termination. That means, if you do not handle the specified signal, the kernel takes the default action, therefore, if you want to keep the process alive, you have to catch the signal.

To answer your question, read the provided man page.

A process can change the disposition of a signal using sigaction(2) or signal(2) .

@Erdal Küçük has already answered your question but here is a sample piece of code so you can understand it better.

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

void handler(int _) {
  (void)_;
  printf("\nEnter a number: ");
  ffush(stdout);
}
int main(void) {

  pid_t pid;

  pid = fork();
  int n = 0;

  if (pid < 0) {
    perror("Can't fork");
  } else if (pid == 0) {
    // Child process
    kill(getpid(), SIGKILL); // Killing the child process as we don't need it
  } else {
    // Parent process
    struct sigaction sg;
    sg.sa_flags = SA_RESTART;
    sg.sa_handler = handler;
    sigaction(SIGINT, &sg, NULL);
    printf("Enter a number: ");
    scanf("%d", &n);
  }
  printf("Value of n = %d", n);

  return 0;
}

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