我需要某种方式让父进程分别与每个子进程通信。
我有一些 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;
}
代码是不言自明的:
- 父 fork ()
- child 从管道中读取()直到 EOF
- 父 writes() 到管道然后 closure()
- 数据已共享,万岁!
从那里你可以做任何你想做的事;只记得检查你的返回值并阅读 dup
, pipe
, fork
, wait
... 手册,它们会派上用场。
还有很多其他方法可以在进程之间共享数据,尽管它们不符合您的“私有(private)”要求,但它们可能会让您感兴趣:
- shared memory "SHM" , 这个名字说明了一切......
- sockets , 如果在本地使用,它们显然效果一样好
- FIFO files基本上是有名字的管道
甚至是一个简单的文件...(我什至使用 SIGUSR1/2 signals 在进程之间发送二进制数据一次...但我不建议这样做哈哈。) 可能还有一些我现在没有考虑的。
祝你好运。
关于c - fork父子通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14170647/