我正在尝试使用UNIX域套接字在C程序和
Python脚本之间进行通信. Python脚本通过UNIX域套接字将数据发送到C程序.
这是我的C程序的相关代码:
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/un.h> #include <sys/types.h> #include <sys/socket.h> #define UNIX_PATH_MAX 100 int main(void) { struct sockaddr_un address; int socket_fd,connection_fd; socklen_t address_length; pid_t child; socket_fd = socket(AF_UNIX,SOCK_STREAM,0); if (socket_fd < 0){ printf("socket() Failed\n"); return 1; } unlink("/tmp/demo_socket"); memset(&address,sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path,UNIX_PATH_MAX,"/tmp/demo_socket"); if (bind(socket_fd,(struct sockaddr *) &address,sizeof(struct sockaddr_un)) != 0) { printf("bind() Failed\n"); return 1; } if(listen(socket_fd,5) != 0) { printf("listen() Failed\n"); return 1; } //----------------WHILE LOOP-----------------------> while((connection_fd = accept(socket_fd,&address_length)) > -1) { . . .(doesn't get any further than this)
这是我用来向套接字发送消息的python脚本:
import socket s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) s.connect("/tmp/demo_socket") print "Sending..." s.send("Hello world") x = s.recv(1024) print x s.close()
python脚本失败,错误“Broken Pipe”. C程序永远不会进入while循环,因为accept()函数失败并返回’-1′.
为什么accept()失败了?我能做些什么才能让它成功?
解决方法
看看
an example I found,你传递绑定的长度似乎不应该计算sockaddr_un中的终止或填充空值.
尝试:
size_t addrlen; const char* sockname = "/tmp/demo_socket"; /* ... */ address.sun_family = AF_UNIX; snprintf(address.sun_path,sockname); addrlen = sizeof(address.sun_family) + strlen(sockname); if (bind(socket_fd,addrlen) != 0) { printf("bind() Failed\n"); return 1; }
附:因此,您不需要memset调用.