简体   繁体   English

收到 SIGUSR1 信号后执行 function 窗体子进程

[英]Execution of a function form child process after receiving a SIGUSR1 signal

I need help about the code below.我需要有关以下代码的帮助。 I want that the child process displayed an我希望子进程显示一个

Hello world !你好世界 !

when perform a kill -USR1 pid from the terminal.当从终端执行kill -USR1 pid时。 Could you help me about that?你能帮我解决这个问题吗? Thank you in advance.先感谢您。

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

Your code is already there.您的代码已经存在。 Give more info in case below details does not help.如果以下详细信息没有帮助,请提供更多信息。

Parent process created is terminating as soon as you run your code.一旦您运行代码,创建的父进程就会终止。 Making the child an Orphan.让孩子成为孤儿。 In that case 'init' process becomes the parent of the child process which continues to live due to the use of 'pause()'在这种情况下,“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");
     }

So, remove the line所以,删除线

kill(pid, SIGUSR1); 

from the parent part.从父部分。 And now if you pass the following command from terminal现在,如果您从终端传递以下命令

kill -10 pid(your child pid) kill -10 pid(你的孩子 pid)

As SIGUSR1 has value 10. Your code already prints out 'Hello World' from the already registered 'hello_signal()' method.由于 SIGUSR1 的值为 10。您的代码已经从已注册的“hello_signal()”方法中打印出“Hello World”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM