我在Ubuntu 16.04和gcc版本5.4.0。我在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);
}
编译器对轮询()的调用有问题。警告信息是
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
有什么想法吗?
发布于 2019-07-30 12:54:22
来自man 2 poll
int民意测验(struct *fds,nfds_t nfds,int timeout); 调用方应该在nfds中指定fds数组中的项数。
所以,您的poll(&fds, -1, -1)
应该是poll(&fds, 1, -1)
编辑:
您还应该检查函数调用的返回值。
它们可能返回一个值,该值指示错误(主要是-1
)并设置errno。
https://stackoverflow.com/questions/57271852
复制相似问题