首页 > 解决方案 > 保持父进程处于活动状态,而子进程将被 SIGINT 信号终止

问题描述

当我深入研究 C 中的 SIGNAL 时,我想知道是否有可能在接收到 SIGINT 信号后保持父进程处于活动状态,但我对在线研究感到有些困惑,因为他们对此没有太多讨论。

是否可以通过忽略父进程的 SIGINT 信号来使用信号处理程序使父进程保持活动状态。

如果是,我应该如何实施?

标签: csignalsforkwait

解决方案


@Erdal Küçük 已经回答了您的问题,但这里有一段示例代码,以便您更好地理解它。

#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;
}

推荐阅读