由父進程創(chuàng)建兩個子進程代碼(父進程創(chuàng)建子進程與主程序調(diào)用子程序有何不同?)
編寫一段程序,使用系統(tǒng)調(diào)用c#創(chuàng)建兩個子進程要編寫一段程序,使用系統(tǒng)調(diào)用在一個進程中產(chǎn)生了一個新的進程,那么產(chǎn)生的進程為原來進程的子進程;你的代碼是什么樣的fork一次產(chǎn)生一個子進程,返回兩次,如果你沒有if else,直接forkfork這樣調(diào)用,那么會產(chǎn)生四個進程,第二次fork產(chǎn)生一個父進程的子進程,一個子進程的子進程;很簡單,打印父進程pid,然后創(chuàng)建子進程,并打印子進程pid,然后再創(chuàng)建一個子進程,并打印pidinclude ltstdioh include ltunistdh include ltstdlibh int main int pid1, pid2printfquotParent#39s PID is %d;1 父進程通過wait和waitpid等函數(shù)等待子進程結(jié)束,這會導(dǎo)致父進程掛起2 如果父進程很忙,那么可以用signal函數(shù)為SIGCHLD安裝handler,因為子進程結(jié)束后, 父進程會收到該信號,可以在handler中調(diào)用wait回收3 如果;主要一個原因是 父進程和子進程共享代碼段,父進程fork出來的子進程同時也會fork自己的子進程,下面代碼已經(jīng)調(diào)試,符合題目要求 include ltstdioh include ltstdlibh include ltunistdh int main pid_t pid_b;pid_t child1, child2*創(chuàng)建兩個子進程*child1 = forkif child1 == 0 *在子進程 1 中調(diào)用 execlp函數(shù)*execlpquotlsquot, quotlsquot,quotlquot, NULL else父進程創(chuàng)建子進程2 如果原來的方式子。
include ltstdlibh include ltsystypesh include ltunistdh int main int p1,p2ifp1=fork printfquotI am child 1\nquotfork else ifp2=fork printfquotI am child 2\nquot;include ltstdioh int main int pid*這里創(chuàng)建了一個子進程1* pid=forkifpid==0printfquotI am son,my pid is dquot,getpidelse ifpid0 *從子進程1返回到父進程時,再創(chuàng)建子進程2;每一個進程都會在退出前 sleep 30秒,從而保證能夠用 ps 看到,編譯 gcc testpidc。
int mainvoid int i=2pid_t pidwhilei ifpid=forklt0 err_sysquotfork error\nquotexit1 else ifpid==0 printfquotChild Thread my pid is %d\nquot,getpidbreakelse;fork三個方法對子進程的操作建立nodechildProcess文件,在其中創(chuàng)建nodechildProjs文件其中就一行代碼如下consolelogquot進程 quot + processargv2 + quot 執(zhí)行quot 換成下面的查看processargvconsole;child2=forkifchild2==1 printfquotChild2 fork error!\nquotexit1 else ifchild2==0 printfquotThe returned value is %d\nIn child2 process\nMy PID is %d\nquot,child2,getpid pri。
*這將創(chuàng)建一個子進程1 * 的pid = fork的如果PID == 0的printf,GETPID“我的兒子,我的PID為%d \ n”否則,如果PID 0 *從子進程返回給父進程,然后創(chuàng)建一個子進程2 *;if PID=fork 0 處理語句 這就是處理的主要部分首先執(zhí)行PID=fork,返回給父進程的是子進程的ID,當然返回的子進程的是0然后判斷PID0,父進程跳過這個判斷,子進程呢,就進入if里面執(zhí)行這不;*fork返回值為0,則創(chuàng)建子進程成功且當前進程為子進程 if pid2=fork == 0 printf quotc\nquot 子進程2輸出’c’ *fork返回值大于0,則當前進程為父進程* else waitNULL。
掃描二維碼推送至手機訪問。
版權(quán)聲明:本文由飛速云SEO網(wǎng)絡(luò)優(yōu)化推廣發(fā)布,如需轉(zhuǎn)載請注明出處。