• 网络超时检测


    getsockopt
    setsockopt
    网络超时检测:
    必要性:避免进程在没有数据时无限制的阻塞
    当设置的时间到,进程从原操作返回继续运行
    3种方式可以:
    1.设置socket的属性
    SO_RCVTIMEO 接收超时
    SO_SNDTIMEO 发送超时

    struct timeval tv;
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    setsockopt(sockfd, SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv));
    5秒接收超时检测。

    2.select也可以超时检测

    3.设置定时器(timer),捕捉SIGALRM信号

    #include <stdio.h>
    #include <signal.h>

    void handler(int sig)
    {
    printf("sig = %d\n", sig);
    }

    int main()
    {
    char buf[100] = "hello";
    //signal(SIGALRM, handler);
    struct sigaction myaction;
    sigaction(SIGALRM, NULL, &myaction);
    myaction.sa_handler = handler;
    myaction.sa_flags &= ~SA_RESTART;
    //myaction.sa_flags |= SA_RESTART;
    sigaction(SIGALRM, &myaction, NULL);


    while(1)
    {
    alarm(2);
    if(fgets(buf, 100, stdin) == NULL)
    {
    //continue;
    break;
    }
    alarm(0);
    printf("buf = %s\n", buf);
    }

    }

  • 相关阅读:
    HDU 2544 (Djikstra)
    HDU 1237(表达式求值)
    HDU1690 (Floyd)
    《大道至简》读后感
    第6周总结
    第8周总结
    第7周总结
    第四周总结
    第5周总结
    java程序
  • 原文地址:https://www.cnblogs.com/spinsoft/p/2582536.html
Copyright © 2020-2023  润新知