阻塞套接字上的接受EAGAIN错误

时间:2009-12-16 21:17:49

标签: linux sockets tcp

我正在使用阻塞套接字来接受连接。我很少遇到这个错误,这使得调试变得困难。接受返回EAGAIN错误。怎么能用于阻塞套接字?

1 个答案:

答案 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;
}