【问题标题】:Execution of a function form child process after receiving a SIGUSR1 signal接收到 SIGUSR1 信号后执行一个函数形式的子进程
【发布时间】:2021-05-04 17:27:27
【问题描述】:

我需要有关以下代码的帮助。 我希望子进程显示一个

世界你好!

当从终端执行kill -USR1 pid时。 你能帮我解决这个问题吗? 提前谢谢你。

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

static int count = 0;
void hello_signal (int sig_num) {
     if (sig_num == SIGUSR1)
     {
         printf ("signal received successfully \ n");
         printf ("Hello, world! \ n");
         count = 1;
     }
}

int main () {
    signal (SIGUSR1, hello_signal);
     pid_t pid = fork ();
     if (pid == 0) {
         printf ("The child has been created");
         pause();
     }
     else if (pid <0) {
         printf ("cannot create the child");
     }
     else {
         // kill (pid, SIGUSR1);
         kill (pid, SIGUSR1);
         printf ("signal sent \ n");
         }
   return 0;
}

【问题讨论】:

    标签: c signals


    【解决方案1】:

    您的代码已经存在。如果以下详细信息没有帮助,请提供更多信息。

    一旦您运行代码,创建的父进程就会终止。让孩子成为孤儿。 在这种情况下,“init”进程成为子进程的父进程,由于使用“pause()”而继续存在

     if (pid == 0) {
         printf ("The child has been created");
         pause();
     }
     else if (pid <0) {
         printf ("cannot create the child");
     }
     else {
         // kill (pid, SIGUSR1);
         kill (pid, SIGUSR1);
         printf ("signal sent \ n");
         }
    

    所以,删除线

    kill(pid, SIGUSR1); 
    

    来自父部分。现在,如果您从终端传递以下命令

    kill -10 pid(你的孩子 pid)

    由于 SIGUSR1 的值为 10。您的代码已经从已注册的“hello_signal()”方法中打印出“Hello World”。

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 2016-03-23
      • 2011-11-24
      • 2013-12-29
      相关资源
      最近更新 更多