c++csocketstcptimespec

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


I have a tcp server running on my localhost. My program connects to this tcp server, which responds with data on connection. I'm using signals elsewhere in the program, so I need this to be non-blocking. Unfortunately, I also need to use clock_gettime. When I do this, the tcp connection hangs. The only alternatives that I can think of are to use pipes, switch over to udp, but those two are not desired results. Relevant code below:

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

compiled with $ g++-4.7 -std=c++11 testtcp1.cpp -lrt, gives result

$ ./a.out
TEST WITHOUT INITIALIZING TIMESPEC:

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

testtcp2.cpp

same as testtcp1.cpp except uncommented the line struct timespec timer;, and changing the message. gives result

$ ./a.out
TEST WITH INITIALIZING TIMESPEC:

and hangs forever.


Solution

  • It isn't hanging, it's spinning, because you're in non-blocking mode, you're ignoring errors, and you're incurring buflen == -1 and errno == EAGAIN/EWOULDBLOCK whenever there is no data. Use blocking mode, or at least handle errors properly.