我正在尝试在 Mac Os X 下使用 AF_UNIX 套接字,并且我制作了一个包含一些信息的结构:
typedef struct
{
int socket;
int conn;
struct sockaddr addr;
}socket_info;
我使用这些功能:
socket_info* server_init(void)
{
socket_info* result=(socket_info*)malloc(sizeof(socket_info));
socklen_t length=sizeof(struct sockaddr);
bzero(&(result->addr),sizeof(struct sockaddr));
result->socket=socket(AF_UNIX,SOCK_STREAM,0);
(result->addr).sa_family=AF_UNIX;
(result->addr).sa_len=sizeof(struct sockaddr);
strcpy((result->addr).sa_data,"./mysock");
bind(result->socket,&(result->addr),length);
listen(result->socket,MAX);
result->conn=accept(result->socket,&(result->addr),&length);
return result;
}
socket_info* client_init(socket_info* info)
{
socket_info* result=(socket_info*)malloc(sizeof(socket_info));
result->socket=socket(AF_UNIX,SOCK_STREAM,0);
while( connect(result->socket,&(info->addr),sizeof(struct sockaddr))==-1)
{
if(errno==ENOENT)
{
sleep(1);
}
else
{
fprintf(stderr,"Error: %d",errno);
free(result);
result=NULL;
}
}
return result;
}
我主要使用它们:
int main(int argc, char** argv)
{
socket_info *server_info, *client_info;
pid_t pid;
int fd[2];
pipe(fd);
pid=fork();
if(pid==0)
{
char buffer[100];
read(fd[0], server_info, sizeof(struct sockaddr));
client_info=client_init(server_info);
read(client_info->socket,buffer,100);
printf("Messaggio ricevuto: %s",buffer);
}
else
{
const char* msg="ciao";
server_info=server_init();
write(fd[1],server_info,sizeof(struct sockaddr));
write(server_info->socket,msg,sizeof(msg));
}
close(fd[0]);
close(fd[1]);
return 0;
}
但是客户端无法连接:而是打印消息:“错误:61”。
可能是什么原因?