1

我有一个 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;}
...

测试tcp1.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

测试tcp2.cpp

与 testtcp1.cpp 相同,只是取消注释该行struct timespec timer;并更改消息。给出结果

$ ./a.out
TEST WITH INITIALIZING TIMESPEC:

并永远挂起。

4

1 回答 1

0

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

于 2014-06-22T03:06:06.803 回答