我正在尝试为我的一门课做作业,但没有教授/同学回复我。所以在你回答之前,请不要给我任何确切的答案!只有解释!
我要做的是编写一个接受两个命令行参数W和T的ac程序(timeout.c),其中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);
}