我需要一些方式,使父进程与每个孩子单独沟通。
我有一些孩子需要与父母单独沟通,而不是其他孩子。
父母是否有任何方式与每个孩子建立一个私人沟通渠道?
例如,一个子对象也可以向父变量发送一个struct变量?
我对这类事情很陌生,所以任何帮助都是值得感激的。谢谢
发布于 2013-01-05 11:05:16
(我假设我们是在讨论linux )
您可能会发现,fork()本身只是重复调用过程,它不处理IPC。
从叉子手册: 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;
}代码是非常清楚的:
在那里你可以做任何你想做的事,只要记得检查你的返回值,并读取dup,pipe,fork,wait.手册,会派上用场的。
还有许多在进程之间共享数据的其他方法,尽管它们不符合您的“私有”要求,但它们对您非常感兴趣:
甚至一个简单的文件..。(我甚至使用SIGUSR1 1/2 信号在进程之间发送二进制数据一次.但我不推荐那样的哈哈。)可能还有更多我现在没想过的。
祝好运。
https://stackoverflow.com/questions/14170647
复制相似问题