我正在使用阻塞套接字来接受连接。我很少遇到这个错误,这使得调试变得困难。接受返回EAGAIN错误。怎么能用于阻塞套接字?
答案 0 :(得分:2)
如果套接字设置了接收超时(使用SO_RCVTIMEO
套接字选项),则超时到期时accept
将返回EAGAIN
。
此代码将演示它(并且还让您研究传递信号的效果):
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#define TESTEXIT(s, f) if (s < 0) { perror(f); exit(1); }
void handler(int x)
{
return;
}
int main()
{
int s;
int r;
struct sockaddr_in sin;
socklen_t sin_len = sizeof sin;
struct timeval timeo = { .tv_sec = 5, .tv_usec = 0 };
signal(SIGUSR1, handler);
s = socket(PF_INET, SOCK_STREAM, 0);
TESTEXIT(s, "socket");
r = listen(s, 10);
TESTEXIT(r, "listen");
r = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof timeo);
TESTEXIT(r, "setsockopt");
r = accept(s, (struct sockaddr *)&sin, &sin_len);
TESTEXIT(r, "accept");
return 0;
}