2013-01-05 102 views
5

我需要一些方法讓父母過程分別與每個孩子溝通。叉子父母子女溝通

我有一些孩子需要與其他孩子分開交流。

父母是否有任何方式與每個孩子建立私人通信渠道?

也可以給孩子一個例子,發給父母一個結構變量?

我是新來的這種事情,所以任何幫助表示讚賞。謝謝

+0

管道! http://www.gnu.org/software/libc/manual/html_node/Pipes-and-FIFOs.html(請記住,您必須在分叉之前創建管道,否則它們將無法通信) –

+2

這取決於平臺。你打算在哪個平臺上運行? –

回答

22

(我只是假設我們在這裏談論的Linux)

正如你可能發現,fork()本身只會重複調用進程,它不處理IPC

從叉手冊:

叉()創建通過複製調用進程的新方法。 這個稱爲孩子的新過程是調用過程的精確副本,稱爲父級過程。

一旦你分叉()將使用管道,最常見的方式處理IPC,特別是如果你想「與每個孩子私人通信chanel」。這裏,類似於一個你可以在pipe手動發現(返回值不檢查)使用的典型和簡單的例子:

#include <sys/wait.h> 
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <unistd.h> 
    #include <string.h> 

    int 
    main(int argc, char * argv[]) 
    { 
     int pipefd[2]; 
     pid_t cpid; 
     char buf; 

     pipe(pipefd); // create the pipe 
     cpid = fork(); // duplicate the current process 
     if (cpid == 0) // if I am the child then 
     { 
      close(pipefd[1]); // close the write-end of the pipe, I'm not going to use it 
      while (read(pipefd[0], &buf, 1) > 0) // read while EOF 
       write(1, &buf, 1); 
      write(1, "\n", 1); 
      close(pipefd[0]); // close the read-end of the pipe 
      exit(EXIT_SUCCESS); 
     } 
     else // if I am the parent then 
     { 
      close(pipefd[0]); // close the read-end of the pipe, I'm not going to use it 
      write(pipefd[1], argv[1], strlen(argv[1])); // send the content of argv[1] to the reader 
      close(pipefd[1]); // close the write-end of the pipe, thus sending EOF to the reader 
      wait(NULL); // wait for the child process to exit before I do the same 
      exit(EXIT_SUCCESS); 
     } 
     return 0; 
    } 

的代碼是不言自明:

  1. 父從管叉()
  2. 孩子在讀(),直到EOF
  3. 家長寫()來管然後關閉(),它
  4. DATAS已經共享,萬歲!

從那裏你可以做任何你想做的事情;只記得檢查你的返回值,並閱讀dup,pipe,fork, wait ...手冊,他們會派上用場。

還有一堆其他方式進程之間共享DATAS,他們migh你感興趣,雖然他們不符合你的「私人」的要求:

或前夕,他們顯然工作一樣好沒有簡單的文件...(我甚至使用SIGUSR1/2 signals在進程之間發送二進制數據一次......但我不會推薦哈哈) 可能還有一些我現在沒有考慮的東西。

祝你好運。