我正在学习 C,这是我的问题:我需要使用套接字 AF_UNIX 连接 2 个进程。 我的问题是:我怎样才能实现这一目标?
我已经尝试过一些结果不佳的方法:
尝试传递 fd。
尝试复制但再次失败,两个进程没有从父进程获取任何消息。
我可以在父级中打开一个套接字,然后使用 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);
}
注意:我并没有尝试使用套接字。
最佳答案
Here is a description unix 套接字和代码示例。
您需要指定一个 fork 进程作为服务器,另一个作为客户端。在服务器中,您必须等待连接。在客户端,您必须建立通信。
链接中是每项服务的示例。不要对代码的长度感到 panic - 大部分都是注释。
请注意,如果您只想在进程之间进行“本地”通信,您可能需要研究 IPC:fifo、共享内存、消息传递。它们更容易实现。
关于c - 如何在 fork-exec 之后在两个进程之间创建套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30305888/