2009-08-06 49 views
3

我有一個C文件看起來像這樣:控制福克斯用C

#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
int main() 
{ 
    pid_t child_pid; 
    printf ("The PID is %d\n", (int) getpid()); 
    child_pid = fork(); 
    if (child_pid != 0) 
    { 
     printf ("this is the parent process, with PID %d\n", 
     (int)getpid()); 
     printf ("the child's PID is %d\n", (int) child_pid); 
    } 
    else 
     printf ("this is the child process, with PID %d\n", 
     (int)getpid()); 
    return 0; 
} 

我需要修改它來產生AA層次結構,看起來像

parent (0) 
    | 
    +---> child (1) 
    | 
    +---> child (2) 
      | 
      +----> child (3) 
      | 
      +----> child (4) 
        | 
        +----> child (5) 
        | 

基本上是一個樹形結構,其中每個第二孩子讓兩個新的孩子。據我瞭解,當我的一個進程中,每個進程都會同時運行。在if語句中添加一個fork()似乎可以正常工作並正確創建進程0到2,因爲只有父級會創建新的分支。但我不知道如何使流程2分叉,而不是1.任何想法?

+1

你有沒有考慮過這個過程的侷限性?何時會停止,爲什麼?它會對操作系統做什麼? (在unix衍生系統上,請考慮閱讀'ulimit'的手冊頁。)只是試圖提供幫助。 – dmckee 2009-08-06 13:28:55

回答

2

那麼,過程1將由第一個叉創建。過程2將由if語句內的fork創建。因此,爲了讓進程2叉過,你叉再次if語句中,如果第二叉沒有返回0

一個例證:

if(fork) { 
    // Inside process 0 
    if(fork) { 
     // still in process 0 
    } else { 
     // in process 2 
     if(fork) { 
      // still in process 2 
     } else { 
      // in prcess 3 
     } 
     // and so on 
    } 
} else { 
    // Inside process 1 
} 
+0

謝謝。這使得這個概念更清晰。 – pypmannetjies 2009-08-06 15:51:41

2

兒童在當時得到了父母的狀態的副本的叉子。

因此,如果家長有一個計數器或其他財產,那麼孩子們將在他們分岔時看到價值(但如果父母隨後改變它)。

2

我不知道你爲什麼要這樣做,但通常只有父進程執行fork。這可能也更容易設計。當您在for循環中執行fork()時,您將直接控制所創建的進程。

請注意,fork()是一個相對昂貴的操作,尤其是如果您想創建多個進程。更輕量級的替代vfork和線程可用,但我不能判斷它們是否也適合您的需求。

+0

任何進程都可以分叉,甚至是兒童。事實上,這就是如何編寫叉炸彈,每個過程分叉兩次,直到系統淹沒。 – paxdiablo 2009-08-06 13:19:53

+0

謝謝pax;我已經更新了我的答案 – Adriaan 2009-08-06 13:43:48

+0

這只是一個練習 - 我永遠不會甘心做一些如此奇怪的事情:) – pypmannetjies 2009-08-06 15:52:24

1

一個古老的問題,但仍然是一個有趣的問題。該man pagefork()告訴我們,返回值:

成功時,在父返回子進程的PID,而在兒童則返回0。失敗時,在父項中返回-1,不創建子進程,並且適當地設置errno。

所以我們知道fork()返回一個0到孩子,我們可以用這個作爲控制機制:

int main() 
{ 
    // Here we're in the parent (0) process 

    if(fork()) // This starts the chain, only the parent will do this 
    if(!fork()) //the child will pass this, the parent will skip it 
    for(count = 0; counter < number_of_processes; counter++) //now the 2nd child loops 
    { 
     if(fork()) 
      if(!fork()); 
     else 
      break; 
    } 

讓我們把一些數字吧:

//parent (18402) 
if(fork()) // spawns 18403, parent 18402 keeps going 
    if(!fork()) // spawns 18404, parent 18402 drops to the end of main() 
    for(count = 0; count < number_of_processes; conter++) // 18404 enters here 
     if(fork()) // 18404 forks 18405 and then goes on 
     if(!fork()); // 18404 spawns 18406 before leaving, 18406 restarts the loop 
     else 
      break; // 18404 breaks out there 
     else 
      break; //18405 leaves the loop here 

所以後我們有一個迭代:

18402 
    | 
    +---> 18403 
    | 
    +---> 18404 
      | 
      +----> 18405 
      | 
      +----> 18406 
        | 

之後,我們將繼續循環兩個新進程,其中第二個將繼續迭代,直到您根據需要進行了多次傳遞。