【发布时间】:2014-04-11 01:59:22
【问题描述】:
我正在尝试为我的一门课程做作业,但没有教授/同学回复我。所以在你回答之前,请不要给我任何确切的答案!只有解释!
我要做的是编写一个 c 程序 (timeout.c),它接受两个命令行参数,W 和 T,其中 W 是子进程在退出之前应该花费的时间量,以秒为单位,T 是在终止子进程并打印出“超时”消息之前,父进程应该等待子进程的时间。基本上,如果 W > T,应该有一个超时。否则,孩子应该完成它的工作,然后不会打印超时消息。
我想做的只是让父进程休眠 T 秒,然后杀死子进程并打印出超时,但是在这两种情况下都不会打印出超时消息。如何检查子进程是否已终止?有人告诉我为此使用 alarm(),但是我不知道该函数有什么用途。
这是我的代码,以防有人想看:
void handler (int sig) {
return;
}
int main(int argc, char* argv[]){
if (argc != 3) {
printf ("Please enter values W and T, where W\n");
printf ("is the number of seconds the child\n");
printf ("should do work for, and T is the number\n");
printf ("of seconds the parent process should wait.\n");
printf ("-------------------------------------------\n");
printf ("./executable <W> <T>\n");
}
pid_t pid;
unsigned int work_seconds = (unsigned int) atoi(argv[1]);
unsigned int wait_seconds = (unsigned int) atoi(argv[2]);
if ((pid = fork()) == 0) {
/* child code */
sleep(work_seconds);
printf("Child done.\n");
exit(0);
}
sleep(wait_seconds);
kill(pid, SIGKILL);
printf("Time out.");
exit(0);
}
【问题讨论】:
-
通过wait/waipid可以得到子进程的状态
标签: c process fork child-process waitpid