【发布时间】:2015-05-18 14:27:48
【问题描述】:
我正在学习 C,这是我的问题:我需要使用套接字 AF_UNIX 连接 2 个进程。 我的问题是:我怎样才能做到这一点?
我已经尝试过一些效果不佳的方法:
试图通过 fd。
尝试复制但再次失败,并且 2 个进程没有从父进程获取任何消息。
我可以在父级中打开一个套接字,然后使用 execl 传递文件描述符吗?还是我应该尝试一些更“复杂”的东西?
编辑:代码 这是P1.c
int main (){
printf("Hello this is process 1\n");
int fd=open("./foo",O_RDWR);
int h=fork();
if(h==0)
{
sleep(2);
dup2(fd,0);//note we will be loosing standard input in p2
execvp("./client",NULL);
}
else
{
printf("This is from p1 process\n");
write(fd,"buf",4);
//do some process with p1
printf("This is end of p1 process\n");
}
return 0;
}
这是 P2.c
int main (int argc, char * argv[]){
int fd=atoi(argv[1]);
char buf[1024];
int n=read(fd,buf,1024);
buf[n]='\0';
printf("This is from p2\n");
write(1,buf,strlen(buf));
exit(EXIT_SUCCESS);
}
注意:我没有尝试使用套接字。
【问题讨论】:
-
你能发布你的代码吗?
-
好的,现在检查代码。
-
最简单的方法是在分叉之前打开套接字,这样fd对双方都可用。
-
在我 fork 之后:父母应该等待连接,孩子应该连接?我应该将 fd 作为 exec 的参数传递吗?