Does this code have logical errors?

I'm a newbie, please be careful! I copied the code from the book:

#include <sys/types.h> #include <signal.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> static int alarm_fired = 0; void ding(int sig) { alarm_fired = 1; } int main(int argc, char* argv[]) { pid_t pid; printf("alarm application starting\n"); pid = fork(); switch(pid) { case -1: perror("fork failed"); exit(EXIT_FAILURE); case 0: sleep(5); kill(getpid(), SIGALRM); exit(EXIT_SUCCESS); } printf("waiting for alarm to go off\n"); (void) signal(SIGALRM, ding); pause(); if (alarm_fired) printf("Ding!\n"); printf("done\n"); exit(EXIT_SUCCESS); } 

As the author wrote:

ding , imitates an alarm clock. The child process waits five seconds before the SIGALRM signal is sent to its parent.


I tried the code above, but after printing alarm application starting

waiting for alarm to go off . So I suspect the code has a logical error. String kill(getpid(), SIGALRM); may be wrong. I'm right?

+4
source share
2 answers

You're right line

 kill(getpid(), SIGALRM); 

incorrect if the child should send a signal to the parent. Be that as it may, he tries to send a signal to himself, as he passes his own pid getpid() (get the process identifier).

You must use getppid() (get the parent process id) so that you can send a message to the parent process, for example:

 kill(getppid(), SIGALRM); 
+4
source

This line:

 kill(getpid(), SIGALRM); 

executed by the child and sends an alarm to itself.

This line:

 signal(SIGALRM, ding); 

Is parental alarm handler set to alarm

And this line is waiting for a signal:

 pause(); 

You need a child to send a signal to the parent not to himself, and then all the dominoes will fall.

+1
source

All Articles