简体   繁体   中英

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. 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()'

 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)

As SIGUSR1 has value 10. Your code already prints out 'Hello World' from the already registered 'hello_signal()' method.

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