使用-O标志

时间:2019-07-30 12:36:05

标签: c sockets polling

我在使用gcc版本5.4.0的Ubuntu 16.04。我在C中有一个相当简单的套接字示例,当我使用优化(-O)进行编译时,该示例失败了(它不进行任何优化)。我将原始代码修整为:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>

int main() {
    struct addrinfo *ai, hints;
    memset(&hints, 0, sizeof hints);
    getaddrinfo(NULL, "7471", &hints, &ai);

    int listen_fd = socket(ai->ai_family, SOCK_STREAM, 0);
    bind(listen_fd, ai->ai_addr, ai->ai_addrlen);
    freeaddrinfo(ai);

    listen(listen_fd, 128);

    struct pollfd fds;
    fds.fd = listen_fd;
    fds.events = POLLIN;
    poll(&fds, -1, -1);
}

编译器在调用poll()时遇到问题。警告消息是

in function ‘poll’,
    inlined from ‘main’ at simplecode.c:25:5:
/usr/include/x86_64-linux-gnu/bits/poll2.h:43:9: warning: call to ‘__poll_chk_warn’ declared with attribute warning: poll called with fds buffer too small file nfds entries
  return __poll_chk_warn (__fds, __nfds, __timeout, __bos (__fds));

实际的运行时错误会更长,但始于:

*** buffer overflow detected ***: ./simplecode terminated

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

来自man 2 poll

  

int poll(struct pollfd * fds,nfds_t nfds,int timeout);

     

调用方应在以下位置指定fds数组中的项目数   nfds。

因此,您的poll(&fds, -1, -1)应该是poll(&fds, 1, -1)

编辑:
您还应该检查函数调用的返回值。
他们可能会返回一个表示错误的值(主要是-1)并设置errno。