【问题标题】:Keeping parent process alive while child process will be terminated by SIGINT signal保持父进程处于活动状态,而子进程将被 SIGINT 信号终止
【发布时间】:2021-12-04 11:10:22
【问题描述】:

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

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

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

【问题讨论】:

  • 忽略 SIGINT 最好通过 sigaction 调用而不是 signal 调用来实现(使用 SIG_IGN)Ubuntu 20.4 上的信号手册页这样说:The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.

标签: c signals fork wait


【解决方案1】:

我想说,没什么好讨论的。

查看signal(7) 的手册页。在标准信号部分,SIGINT 的默认操作是程序终止。这意味着,如果您不处理指定的信号,内核将采取默认操作,因此,如果您想保持进程处于活动状态,则必须捕获该信号。

要回答您的问题,请阅读提供的手册页。

进程可以使用sigaction(2)signal(2) 更改信号的处置。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-05
      • 2021-09-16
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 2016-03-22
      相关资源
      最近更新 更多