【发布时间】:2015-10-13 16:45:05
【问题描述】:
我有一个创建“n”个子进程的循环。这些进程进入一个单独的程序并休眠“x”秒,然后返回退出状态“x”。问题是当我尝试等待每个单独的进程时。似乎我的 wait() 调用等待最后一个进程,然后程序退出。我想要这样,无论哪个孩子退出,我都可以打印他们的信息,然后等待下一个孩子退出并打印他们的信息......等等。
代码:
int main()
{
char input[12];
int n, i, ch;
pid_t pid;
int status={0};
printf("Enter an integer: ");
fgets(input, 12, stdin);
if (input[10] == '\n' && input[11] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }
rmnewline(input);
n = atoi(input);
for(i=0; i<=n-1; i++)
{
pid = fork();
if(pid == 0)
execl("/home/andrew/USP_ASG2/sleep", "sleep", NULL);
}
for(i=0; i<=n-1; i++)
{
wait(&status);
if(WIFEXITED(status))
{
int exitstat = WEXITSTATUS(status);
printf("Child %d is dead with exit status %d\n", pid, exitstat);
}
}
}
输出:
In child 15930
In child 15929
In child 15928
Child 15930 is dead with exit status 5
Child 15930 is dead with exit status 5
Child 15930 is dead with exit status 5
【问题讨论】:
-
顺便说一句:就风格而言,
i<=n-1会比i<n更清晰 -
@WeatherVane 否。由于数组偏移量从零开始,
for ( i = 0; i < n; i++ )是在 C 中编写for循环的规范方法。只需谷歌“c for loop”。查看许多示例:codingunit.com/…stackoverflow.com/questions/4604500/…tutorialspoint.com/cprogramming/c_for_loop.htmthegeekstuff.com/2012/12/c-loops-examples 此外,省略减法可能会略微提高性能,尤其是在 x86 等寄存器匮乏的架构上。 -
@AndrewHenle 你确定你正确阅读了我的评论吗?如果
n==0,循环控制i<=n-1在未签名时可能会发疯。我写的是“clearer as”,而不是“clearer than”。 -
@WeatherVane 我似乎确实误读了您的评论。我应该认识到这一点。是的,
i < n会更清楚。好吧,我们意见一致。
标签: c parent-child wait exit-code waitpid