unix socket服务器

只能处理单个消息,一发一收。

 

int loop(void) {   struct sockaddr_un client_addr;  int server_socket, client_socket;  socklen_t len;  struct message msg;  struct answer ans;  fd_set fds, fds_bak;  int maxfd, index, ret = 0;  bool fresh = TRUE;  pthread_t read_thread = 0;  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

 server_socket = socket_local_server(SOCKET_PATH, SOCK_STREAM);  if (server_socket == FALSE) {   pthread_mutex_destroy(&mutex);   return FALSE;  }

 maxfd = server_socket;  FD_ZERO(&fds);  FD_ZERO(&fds_bak);  FD_SET(server_socket, &fds_bak);

 len = sizeof(client_addr);  while (1) {   fds = fds_bak;   struct timeval timeout = { 0, 50000 /* 50ms */ };   maxfd = update_maxfd(fds, maxfd);

  ret = select(maxfd + 1, &fds, NULL, NULL, &timeout);   if (ret == 0 || (ret == -1 && errno == EINTR)) {    continue;   } else if (ret < 0) {    PRT("socket selectting failed(%s).\n", strerror(errno));    goto fail;   }

  for (index = 0; index <= maxfd; index++) {    if (!FD_ISSET(index, &fds))     continue;

   if (index == server_socket) {     client_socket = accept(server_socket, (struct sockaddr *)&client_addr,           &len);     if (client_socket < 0) {      PRT("accept client failed(%s).\n", strerror(errno));      goto fail;     }     set_socket_nonblock(client_socket);     if (client_socket > maxfd) {      maxfd = client_socket;     }     FD_SET(client_socket, &fds_bak);    } else {     memset((HI_VOID *)&msg, 0, sizeof(struct message));     if ((read(client_socket, (HI_VOID *)&msg,      sizeof(struct message))) != sizeof(struct message)) {      close(server_socket);      close(client_socket);      pthread_mutex_destroy(&mutex);      return HI_FAILURE;     } else {      /*process recvmsg and sendback result*/                  if ((write(client_socket, (HI_VOID *)&ans,       sizeof(struct answer))) != sizeof(struct answer)) {       close(server_socket);       close(client_socket);       pthread_mutex_destroy(&mutex);       return HI_FAILURE;      }      close(client_socket);      FD_CLR(index, &fds_bak);     }    }   }  } }

posted @ 2019-02-13 15:30  渺一粟之沧海  阅读(463)  评论(0编辑  收藏  举报