管道是单向的,并使用插座有点IPC事情似乎痛苦。
我建议您使用socketpair()
。您可以将它们视为双向管道。
这里就是家长发送字符到其child.Then孩子使它大写,并将其发送回父的例子。(这是从beej的教程)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void)
{
int sv[2]; /* the pair of socket descriptors */
char buf; /* for data exchange between processes */
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
perror("socketpair");
exit(1);
}
if (!fork()) { /* child */
read(sv[1], &buf, 1);
printf("child: read '%c'\n", buf);
buf = toupper(buf); /* make it uppercase */
write(sv[1], &buf, 1);
printf("child: sent '%c'\n", buf);
} else { /* parent */
write(sv[0], "b", 1);
printf("parent: sent 'b'\n");
read(sv[0], &buf, 1);
printf("parent: read '%c'\n", buf);
wait(NULL); /* wait for child to die */
}
return 0;
}
你也可以在两个方向上轻松使用两根管道。
您是否尝试过沿管道传递一个管道描述符给父进程,该进程正在侦听响应? – phyrrus9
我们还可以看到一些代码 – phyrrus9
您可以为每个子进程分别输入一个管道和一个输出管道,而父进程将使用另一端。如果你可以对管道使用'stdin'和'stdout',那么效果会更好。 套接字是另一种选择。 http://beej.us/guide/bgipc/output/html/singlepage/bgipc.html是一个很好的信息来源。理查德史蒂文斯关于UNIX编程的书籍也是如此。 – PSkocik