cmc*_*cmc 35
(我假设我们在这里谈论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;
}
Run Code Online (Sandbox Code Playgroud)
代码非常简单:
从那里你可以做任何你想做的事情; 只记得检查返回值和阅读dup,pipe,fork,wait...手册,他们会派上用场.
还有许多其他方法可以在进程之间共享数据,尽管它们不符合您的"私有"要求,但它们对您很感兴趣:
甚至是一个简单的文件...(我甚至使用SIGUSR1/2 信号在进程之间发送一次二进制数据......但我不建议那么哈哈.)可能还有一些我没想到的权利现在.
祝好运.
| 归档时间: |
|
| 查看次数: |
25975 次 |
| 最近记录: |