【问题标题】:Fork parent child communicationfork 父子通信
【发布时间】:2012-12-19 16:31:48
【问题描述】:

我需要某种方式让父进程分别与每个子进程进行通信。

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

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

例如,孩子也可以向父母发送结构变量吗?

我是这类事情的新手,因此感谢您提供任何帮助。谢谢

【问题讨论】:

标签: c fork ipc


【解决方案1】:

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

您可能已经发现,fork() 本身只会复制调用过程,它不处理 IPC

来自 fork 手册:

fork() 通过复制调用进程来创建一个新进程。 新进程,称为子进程,是 调用进程,称为父进程。

fork() 后处理 IPC 的最常用方法是使用管道,特别是如果您想要“与每个孩子的私人通信通道”。这是一个典型且简单的使用示例,类似于您可以在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. 数据已共享,万岁!

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

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

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

祝你好运。

【讨论】:

  • 如果我不在父代码块中写wait(NULL)怎么办?
  • @BhawandeepSingla 父母将终止进程,即使孩子仍在处理!你也可以在 return 0 之前写 wait(NULL);
  • 你可能应该展示fork()返回-1的情况。
  • 还要在双方都有读/写,你需要调用pipe()两次。如果用户想要完整的 IPC,则可能是必需的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 2017-12-26
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
相关资源
最近更新 更多