我是新手,请温柔!我从书中复制了代码:
#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);
}
正如作者所写:
ding
SIGALRM
,模拟闹钟。子进程在向其父进程发送信号之前等待五秒钟。
我试过上面的代码,但打印后没有反应alarm application starting
waiting for alarm to go off
.所以我怀疑代码有逻辑错误。该行kill(getpid(), SIGALRM);
可能是错误的。我对吗?