我對使用fork(),sleep()和wait()在 c 中創建行程有點困惑。取下面的一段代碼:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
for(int i=0;i<5;i )
{
if(fork() == 0)
{
for(int i =0; i<5; i )
{
printf("pid:%d email:myemail \n",getpid());
sleep(1);
}
printf("%d\n",getpid());
exit(0);
}
wait(NULL);
}
}
這段代碼執行后,執行行程但不洗掉5個行程的重復。我對這個程序有點困惑。
初始行程創建 5 個子行程,并等待它們完成。每個子行程執行 5 次重復,其中在每次重復中:
列印訊息 pid: PID email: USER_EMAIL 其中 PID 是行程的子 PID,而 USER_EMAIL 是電子郵件
使用 sleep 呼叫暫停其操作 1 秒(一次)
父行程在完成后列印子行程的 PID
PS我編輯代碼
uj5u.com熱心網友回復:
@mixalispetros,你有很多事情需要修復,而且它們都必須一起修復,你的代碼才能按預期作業。
exit(0);
for (int i = 0; i < 5; i ) {
wait(NULL);
}
該程序結束于exit(0)。 wait永遠不會被呼叫。
if (fork() == 0) {
// what code runs here? The code in the new process
}
什么代碼在fork()條件中運行?該新行程的代碼。應該運行哪個行程wait()?在最初的程序。所以除了在 a 之后exit,wait()也在錯誤的程序中。
把它移到哪里?5 個子行程的for回圈wait()。為什么會有 5 個子行程 to wait()?因為在進入 5 s回圈之前,我們已經啟動了所有 5個子行程。wait()
在wait()小號不能只是外面發生的子行程有條件方框外,還呼吁周圍的回圈fork()。
我對在 c 中使用 fork()、sleep() 和 wait() 創建行程有點困惑
這是混淆。經常參考檔案以保持原樣。請記住,fork()回傳兩次 - 在原始行程中(回傳新行程的行程 ID)和在新行程中(回傳0)。 wait(), 將等待下一個子行程退出。
總之,把wait環以外的環fork()的孩子行程。這也將把它移到child行程中執行的代碼塊之外。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
// this loop creates 5 processes
for (int i = 0; i < 5; i ) {
if (fork() == 0) {
printf("Child %d, PID %d\n", i, getpid());
sleep(i);
exit(0);
}
}
// now, all subprocesses were started
// wait for the same number of child processes to end
for (int i = 0; i < 5; i ) {
wait(NULL);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364675.html
上一篇:重新分配期間的跟蹤/斷點陷阱
