我有一個循環創建'n'子進程。進程進入一個單獨的程序,睡眠'x'秒,然後返回退出狀態'x'。問題是當我嘗試等待每個單獨的進程時。看起來,我的wait()調用等待最後一個進程,然後程序退出。我希望這樣,以便哪個孩子退出,我可以打印他們的信息,然後等待下一個孩子退出並打印他們的信息......等等。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
@WeatherVane No.對於基於零的數組偏移,'for(i = 0; i < n; i ++)'是在C中編寫'for'循環的標準方式。只需要Google「c for循環」。看到很多例子:http://www.codingunit.com/c-tutorial-for-loop-while-loop-break-and-continue http://stackoverflow.com/questions/4604500/use-of-for-in -ac-sharp-application http://www.tutorialspoint.com/cprogramming/c_for_loop.htm http://www.thegeekstuff.com/2012/12/c-loops-examples/此外,省略減法可能導致性能略有改善,特別是在像x86這樣需要註冊的架構上。 –
@AndrewHenle你確定你看過我的評論corerctly?如果'n == 0',循環控制'i <= n-1'在無符號時會發生什麼。我寫得「更清晰」,而不是「比」更清晰。 –