#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/errno.h>
#include <stdlib.h>
int main()
{
char line[128];
int seconds;
pid_t pid;
char message[64];
while(1)
{
printf("Alarm > ");
if(fgets(line,sizeof(line),stdin) == NULL)
exit(0);
if(strlen(line) <= 1)
continue;
/*
parse input line into seconds (%d) and a message (%64[^\n]),
consisting of up to 64 characters separated from the seconds by whitespace
*/
if(sscanf(line,"%d %64[^\n]",&seconds,message) < 2)
{
fprintf(stderr,"Bad command\n");
}
else
{
pid = fork();
if(pid == (pid_t)-1)
{
printf("Fork Error!\n");
exit(0);
}
else
{
if(pid == (pid_t)0)
{
sleep(seconds);
printf("(%d) %s\n",seconds,message);
exit(0);
}
else
{
do
{
pid = waitpid((pid_t)-1,NULL,WNOHANG);
if(pid == (pid_t)-1)
{
printf("wait for child\n");
exit(0);
}
}while(pid != (pid_t)0);
}
}
}
}
return 0;
}
进程版本的闹钟
最新推荐文章于 2023-03-01 09:00:00 发布