[英]fork() and wait() in c while loop?
我在c中有這個小程序,我試圖了解它是如何工作的,這是一個簡單的while循環,使用fork()
和wait()
在命令行上打印出幾行,我的能力正在發生
for (i = 1; i <= 3; i++) /*simple while loop, loops 3 times */
{
pid = fork(); /*returns 0 if a child process is created */
if(pid == 0){ /*pid should be a 0 for first loop */
printf("Hello!\n"); /*we print hello */
return (i); /*will this return i to the parent process that called fork? */
} else { /*fork hasn't returned 0? */
pid = wait(&j); /*we wait until j is available? */
printf("Received %d\n", WEXITSTATUS(j)); /*if available we print "received (j)" */
}
}
該程序應該打印:
Hello!
Received 1
Hello!
Received 2
Hello!
Received 3
當子進程之一返回i
,父進程是否以&j
等待它? 這真的讓我感到困惑,任何幫助將不勝感激。
在循環的每次迭代中, fork()
創建一個子進程。 子進程打印Hello!
並將i
返回系統。 父進程在wait()
上阻塞,直到子進程完成執行。 j
將包含子進程返回到系統的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.