c - fork父子通信

标签 c fork ipc

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

我有一些 child 需要与其他 child 分开与家长交流。

有没有办法让 parent 与每个 child 都有一个私有(private)的沟通 channel ?

例如, child 也可以向 parent 发送一个结构变量吗?

我是这类事情的新手,所以非常感谢您的帮助。谢谢

最佳答案

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

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

From fork manual:

fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent.

forked() 后处理 IPC 的最常见方法是使用管道,特别是如果您想要“与每个 child 的私有(private)通信 channel ”。这是一个典型且简单的使用示例,类似于您可以在 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. 父 fork ()
  2. child 从管道中读取()直到 EOF
  3. 父 writes() 到管道然后 closure()
  4. 数据已共享,万岁!

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

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

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

祝你好运。

关于c - fork父子通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14170647/

相关文章:

python - 从 Python 发出系统调用,获取输出文件名

c++ - 你能在 Arduino (C/C++) 中生成 128 位无符号整数吗?

c - [APUE]fork后parent和child共享相同的文件偏移量吗?

bash:包含 fork 进程的脚本在通过反引号执行时挂起

c# - 从 Windows 服务接收通知

c - 如何确定 DBus 消息中 "array of structs"的长度?

C - 计算文件中字母的出现次数 - 错误 139 : Segmentation fault

c++ - 在 cmake 中启用 Qspectre 和 Control Flow Guard 开关

linux - 如何知道linux中的执行时间

c++ - 如何在 Windows 中访问继承的匿名管道 HANDLE,而不是 stdout、stderr 和 stdin?