(我只是假设我们在这里谈论的是 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;
}
代码非常不言自明:
- 父分叉()
- 子级从管道读取()直到 EOF
- 父级写入()到管道然后关闭()它
- 数据已共享,万岁!
从那里你可以做任何你想做的事;请记住检查您的返回值并阅读dup、pipe、fork、wait...手册,它们会派上用场的。
还有很多其他方法可以在进程之间共享数据,尽管它们不符合您的“私有”要求,但您可能会感兴趣:
甚至是一个简单的文件...(我什至使用 SIGUSR1/2 signals 在进程之间发送二进制数据一次...但我不建议这样做哈哈。)
可能还有一些我现在没有想到的。
祝你好运。