1

我正在尝试在 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”。
可能是什么原因?

4

1 回答 1

3

你有两个主要问题:

  1. 你有一个经典的比赛条件。如果客户端在服务器设置为监听之前尝试连接,客户端将收到错误消息。

  2. 您的服务器不会检查任何错误,因此它可能会失败并且您不会知道。

在任何一种情况下,你都会得到你得到的错误(连接被拒绝)。

My money is on the first problem. If you flip the client and server so the child is the server, it will likely go from "happening not to work" to "happening to work". Most operating systems let the child run first because that saves a ton of memory and eliminates huge numbers of page faults in the typical case where the child just calls exec.

于 2012-05-02T11:52:50.183 回答