listenfd ---- accept事件

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Linux 中,可以使用 `select` 或 `poll` 函数来实现 accept 超时。以下是使用 `select` 函数的示例代码: ```c #include <sys/types.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <errno.h> int main() { int listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { perror("socket"); return -1; } int on = 1; setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(12345); addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(listenfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("bind"); return -1; } if (listen(listenfd, 10) < 0) { perror("listen"); return -1; } fd_set rfds; FD_ZERO(&rfds); FD_SET(listenfd, &rfds); struct timeval tv; tv.tv_sec = 5; // 设置超时时间为 5 秒 tv.tv_usec = 0; int ret = select(listenfd + 1, &rfds, NULL, NULL, &tv); if (ret == -1) { perror("select"); return -1; } else if (ret == 0) { printf("select timeout\n"); return -1; } else { int connfd = accept(listenfd, NULL, NULL); if (connfd < 0) { perror("accept"); return -1; } // 处理连接 } close(listenfd); return 0; } ``` 在上面的代码中,我们使用 `select` 函数设置了一个 5 秒的超时时间,在超时时会输出 "select timeout" 并返回 -1。如果在超时时间内有连接到来,就会执行 accept 函数并返回连接的套接字。如果 accept 函数出错,会返回 -1 并打印错误信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值