叉父母孩子沟通

时间:2013-01-05 09:57:56

标签: c fork ipc

我需要一些方法让父进程分别与每个孩子进行通信。

我有些孩子需要与其他孩子分开与父母沟通。

父母是否有办法与每个孩子建立私人沟通渠道?

例如,孩子也可以向父母发送一个struct变量吗?

我是这些事情的新手,所以任何帮助都会受到赞赏。谢谢

1 个答案:

答案 0 :(得分:31)

(我只是假设我们在这里谈论linux)

正如您可能发现的那样,fork()本身只会复制调用进程,它无法处理IPC

  

来自fork手册:

     

fork()通过复制调用进程来创建一个新进程。   这个被称为孩子的新过程完全相同   调用过程,称为父母。

分叉()后处理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. 数据已经分享,万岁!
  5. 从那里你可以做任何你想做的事;只需记住检查您的返回值并阅读duppipeforkwait ...手册,它们就会派上用场。

    还有许多其他方法可以在进程之间共享数据,虽然它们不符合您的&#34;私有&#34;要求:

    甚至是一个简单的文件...(我甚至使用SIGUSR1 / 2 signals在进程之间发送一次二进制数据......但我不推荐哈哈。) 可能还有一些我现在没有想到的事情。

    祝你好运。

相关问题