【发布时间】:2020-11-27 13:28:14
【问题描述】:
编写一个模拟闹钟的C程序。在主函数中,你 fork 一个子进程, 并且子进程休眠5秒(秒数是命令行 参数,请参见下面的示例运行),之后子进程发送信号 (SIGALRM) 到其父进程。父进程在fork子进程之后, 暂停,在收到 SIGALRM 信号后,打印出一条消息“Ding!”。这 以下是示例运行
$ ./警报 5
报警应用程序启动
等待闹钟响起
叮!
完成
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include<signal.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <stdlib.h>
void Dingdong()
{
printf("Ding!");
exit(1);
}
int main(int argc, char *argv[])
{
if(argc!=3)
{
printf("How much seconds you want to sleep the child process\n");
}
int PauseSecond=(argv[1]);
{
if(fork()==0)
{
printf("waiting for alarm to go off\n");
printf("%d second pause",PauseSecond);
sleep(PauseSecond);
kill(getpid(),SIGALRM);
}
else {
printf("Alarm application starting\n", getpid());
signal(SIGALRM,Dingdong);
printf("done");
}
}
}
【问题讨论】:
标签: c fork parent-child computer-science alarm