2013-01-05 104 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在进程之间发送二进制数据一次......但我不会推荐哈哈) 可能还有一些我现在没有考虑的东西。

祝你好运。