繁体   English   中英

初始化timespec时,非阻塞TCP套接字挂起(C ++)

[英]Non-Blocking TCP Socket hangs when timespec initialized (C++)

我的本地主机上运行着一个tcp服务器。 我的程序连接到该tcp服务器,该服务器在连接时以数据响应。 我在程序的其他位置使用信号,因此我需要使其不受阻塞。 不幸的是,我还需要使用clock_gettime 当我这样做时,tcp连接挂起。 我能想到的唯一替代方法是使用管道,切换到udp,但是这两个不是理想的结果。 相关代码如下:

tcpsens.h:

....
std::string tcpsens::getstr(void){
    int outsock;
    struct sockaddr_in servaddr;
    outsock = socket(AF_INET,SOCK_STREAM,0);

    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = ip_addr;
    servaddr.sin_port=htons(port);

    if (fcntl(outsock, F_SETFL, O_NDELAY | O_NONBLOCK) < 0) {
            perror("Can't set socket to non-blocking");
            exit(0);
        }

    connect(outsock, (struct sockaddr *)&servaddr, sizeof(servaddr));
    while(1) {
        buflen=recv(outsock,buf,255,0);
        if (buflen>0){
            buflen=-1;}
        else if (buflen==0){
            break;}
        //sleep(1);
        //printf("still looping.\n");
    }
    close(outsock);
    return buf;
}
float tcpsens::gettruespeed(){
    float speed,val;
    buffer = getstr();
    sscanf(buffer.c_str(),"%f,%f\n",&speed,&val);
    return speed;}
...

testtcp1.cpp

#include <stdio.h>
#include "tcpsens.h"
#include <string>
#include <iostream>
#include <sys/time.h>
#include <time.h>


int main(void){
        //timing functions
        //struct timespec timer;

        // initialize the tcpsensor
        tcpsens t;

        // connect to tcp and get sensor and speed reading
        std::cout << "TEST WITHOUT INITIALIZING TIMESPEC:\n\n";
        std::cout << "expecting value of ~0.00, got " << t.gettruespeed() << "\n";
        std::cout << "expecting value ~0.00, got " << t.getsensval() << "\n";

        return 0;
}

$ g++-4.7 -std=c++11 testtcp1.cpp -lrt ,得到结果

$ ./a.out
TEST WITHOUT INITIALIZING TIMESPEC:

expecting value of ~0.00, got 0
expecting value ~0.00, got 0

testtcp2.cpp

与testtcp1.cpp相同,但未注释行struct timespec timer; ,然后更改消息。 给出结果

$ ./a.out
TEST WITH INITIALIZING TIMESPEC:

并永久悬挂。

它没有挂起,它正在旋转,因为您处于非阻塞模式下,您忽略了错误,并且每当没有数据时就会产生buflen == -1errno == EAGAIN/EWOULDBLOCK 使用阻止模式,或至少正确处理错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM