接受套接字函数超时 [英] Timeout on an accept socket function

查看:34
本文介绍了接受套接字函数超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在接受套接字函数上设置超时但没有成功.我希望接受功能块直到超时延迟结束.是否可以不设置接受功能非阻塞?我尝试了很多可能性都没有成功.

I'm trying to set a timeout on an accept socket function without success. I would like the accept function blocks until the end of the timeout delay. Is it possible without setting the accept function non-blocking ? I have tried out many possibilities without success.

感谢您的回答.

下面是我的代码:

struct timeval tv;
fd_set readfds;

tv.tv_sec = 1;
tv.tv_usec = 0;

int s, s_remote;
struct sockaddr_un remote;
struct sockaddr_un local;

if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  perror("socket");
  exit(1);
}

FD_ZERO(&readfds);
FD_SET(s, &readfds);

if (select(s+1, &readfds, NULL, NULL, &tv) > 0) {

  printf("Waiting for a connection...\n");

  memset(&local, 0, sizeof(local));
  local.sun_family = AF_UNIX;
  strcpy(local.sun_path, SOCK_PATH);
  unlink(local.sun_path);

  if (bind(s, (struct sockaddr *)&local, sizeof(local)) == -1) {
    perror("UnixSocketClient :: error bind.\n");
    close(s);
    return -1;
  }

  if (listen(s, 5) == -1) {
    perror("UnixSocketClient :: error listen.\n");
    close(s);
    return -1;
  }

  socklen_t remote_len = sizeof(remote);
  printf("Accept :\n\r");

  if ((s_remote = accept(s, (struct sockaddr *)&remote, &remote_len)) == -1) {
    perror("UnixSocket :: error accept.\n");
    return -1;
  }
  printf("Client accepted\n\r");
}

推荐答案

你的代码毫无意义.您必须致电:

Your code makes no sense. You have to call:

  • socket()
  • 绑定()
  • 听()
  • select()
  • 接受()

按那个顺序.

这篇关于接受套接字函数超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆