2011-09-01 121 views
5

我想創建一個使用fork()創建新進程的程序。示例輸出應如下所示:fork()子進程和父進程

這是子進程。我的pid是733,父母的ID是772.
這是父進程。我的pid是772和我的孩子的id是773

這是我如何編碼的我的程序:

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), fork()); 

    return 0; 
} 

這將導致輸出:

這是孩子的過程。我的pid是22163,父母的ID是0.
這是子進程。我的pid是22162,我的父母的編號是22163.

爲什麼打印語句兩次,以及如何在第一個句子顯示子標識後正確顯示父母的ID?

編輯:

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
int pid = fork(); 

if (pid == 0) { 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid()); 
} 
else { 
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), pid); 
} 

return 0; 
} 
+2

您的程序不會嘗試在任何地方打印單詞「父進程」。它們不在節目文本中,你爲什麼期望它們被打印? –

+3

'人叉'。閱讀。理解單詞。如果您沒有任何方法可以自己查找答案,請轉到StackOverflow。你將成爲這種體驗的更好的程序員。 – asveikau

+2

另外,'fork'不會將父進程ID返回給子進程。它返回0給孩子和孩子的ID給父母。這就是你如何知道哪個是哪個。 –

回答

9

首先閱讀fork man page以及getppid/getpid手冊頁。

從叉的

成功時,子進程的PID在父的 線程執行的返回,以及0 執行的孩子的線程返回。失敗時,-1將返回父代的上下文中, 將不會創建子進程,並且將適當地設置errno。

所以這應該是下降的

if ((pid=fork())==0){ 
    printf("yada yada %u and yada yada %u",getpid(),getppid()); 
} 
else{ /* avoids error checking*/ 
    printf("Dont yada yada me, im your parent with pid %u ", getpid()); 
} 

以線條爲你的問題:

這是孩子的過程。我的pid是22163,父母的ID是0.

這是子進程。我的PID是22162,我的父母的ID是 22163.

fork()printf之前執行。所以當它完成時,你有兩個進程執行相同的指令。因此,printf將執行兩次。撥打fork()將返回子進程的0,並將子進程的pid返回到父進程。

你得到兩個正在運行的進程,每一個將執行此 指令 聲明:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

printf ("... My pid is %d and my parent's id is %d",getpid(),22163); 

把它包起來,上面的線是孩子,指定其pid。第二行是父進程,指定其id(22162)及其子節點(22163)。

+0

它會打印兩次,因爲...(來自fork的人):創建新的子進程後,兩個進程都將執行fork()系統調用之後的下一條指令。因此,我們必須將父母與孩子區分開來。這可以通過測試fork()的返回值來完成 – Icarus

+0

非常感謝,這是一個很棒的故障。我編輯了我上面修改過的代碼。它似乎正常工作。你介意重新檢查一下,看看我的邏輯是正確的嗎? – raphnguyen

+0

@raphnguyen每個人都應該調用'getppid()'來獲取他們父進程的id。在您的示例中,父進程將打印其子進程標識。 – Tom

0

在打印兩次,因爲您呼叫的printf兩次,一次在你的程序的執行,一旦在叉。嘗試從printf調用中取出fork()。

2

它正在打印語句兩次,因爲它正在爲父級和子級打印它。父爲0

嘗試這樣的事情父ID:

pid_t pid; 
pid = fork(); 
if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid()); 
else 
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid()); 
0

這是得到正確的輸出正確的方式....但是,孩子的父ID也許有時打印爲1,因爲父進程終止,並且pid = 1的根進程控制着這個孤立進程。

pid_t pid; 
pid = fork(); 
if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
     is %d.\n", getpid(), getppid()); 
else 
    printf("This is the parent process. My pid is %d and my parent's 
     id is %d.\n", getpid(), pid);