叉父母孩子沟通

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

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

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

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

我对这些事情不熟悉,所以对任何帮助表示赞赏。 谢谢

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

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

从fork手册:

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

fork()后最常用的处理IPC的方法是使用管道,特别是如果你想要“与每个孩子一起使用私人通信”。 这是一个典型且简单易用的示例,类似于您在pipe手册中可以找到的示例(不检查返回值):

  #include  #include  #include  #include  #include  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. 数据已经分享,万岁!

从那里你可以做任何你想做的事情; 只记得检查你的返回值并阅读duppipeforkwait …手册,它们会派上用场。

还有许多其他方法可以在进程之间共享数据,虽然它们不符合您的“私有”要求,但它们对您很感兴趣:

  • 共享内存“SHM” ,这个名字说明了一切……
  • sockets ,如果在本地使用,它们显然效果很好
  • FIFO文件基本上是带有名称的管道

甚至是一个简单的文件…(我甚至使用SIGUSR1 / 2 信号在进程之间发送一次二进制数据……但我不建议那么哈哈。)可能还有一些我没想到的权利现在。

祝好运。