I am a newbie,please be gentle!I copied the code from a 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 had written:
ding,simulates an alarm clock.the child process wait for five
seconds before sending aSIGALRMsignal to its parent.
I tried the code above,but it has no response after printing alarm application starting
waiting for alarm to go off.So I am suspecting that the code has logic error.The line kill(getpid(), SIGALRM); may be wrong.Am i right?
You are right, the line
is wrong if the child is to send a signal to it’s parent. As it is, it’s trying to send a signal to himself, as he is passing his own pid by
getpid()(get process id).You should use
getppid()(get parent process id) so you can send the message to the parent process, like this: