gpt4 book ai didi

c - 是否等待子进程终止 - C

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:50 24 4
gpt4 key购买 nike

我正在尝试为我的一门课做作业,但没有教授/同学回复我。所以在你回答之前,请不要给我任何确切的答案!只有解释!

我要做的是编写一个 c 程序 (timeout.c),它接受两个命令行参数 W 和 T,其中 W 是子进程在退出前应该花费的时间(以秒为单位),T 是在终止子进程并打印出“超时”消息之前,父进程应等待子进程的时间量。基本上,如果 W > T,应该有超时。否则, child 应该完成它的工作,然后不会打印超时消息。

我想做的只是让父进程休眠 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);
}

最佳答案

虽然 waitpid 会让您获得子进程的返回状态,但它的默认用法会强制父进程等待直到子进程终止。

但是您的要求(如果我理解正确的话)只希望父级等待一定时间,可以使用 alarm() 来做到这一点。

然后,您应该使用带有特定选项的 waitpid(),如果子进程尚未退出则立即返回(研究 api 的参数)。所以如果 child 没有退出,你可以杀死它,否则你已经收到它的返回状态。

关于c - 是否等待子进程终止 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23002213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com