使用select()系统调用实现poll()

时间:2017-04-19 11:15:03

标签: c linux sockets unix select

static int send_dg(...)
{
    ...
      const u_char buf;
      int buflen;
      struct pollFd pfd[1];

      /* Create NON-Blocking UDP socket */
      pfd[0].fd = socket(PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0);

      /* Connect to the server */
      connect(pfd[0].fd, serverAddress, serverLength);

      /* Make socket as NON-BLOCKING */
      int flag = __fcntl(pfd[0].fd, F_GETFL);
      __fcntl(pfd[0].fd, F_SETFL, flag|O_NONBLOCK);

      pfd[0].events = POLLOUT;

      /* GLIBC: Below poll() system call returns 1 */
      /* Unlike uClibc, ZERO timeout poll returns 
      immediately even if there is NO event on FD */
      poll(pfd, 1, 0);

      /* Send the UDP datagram to the server */
      send(pfd[0].fd, buf, buflen, MSG_NOSIGNAL);
    ...
}

在上面的逻辑中,我应该使用select()系统调用来实现我自己的poll()。我可以用下面的代码替换poll(fd, 1, 0);吗?会选择返回1吗?

int sock_id = pfd[0].fd;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
select(sock_id+1, (fd_set *)NULL, (fd_set *)NULL, (fd_set *)NULL, &timeout);

0 个答案:

没有答案