-1

I am using the read() function to read data from a socket. But sometimes it will block and program will hang.

So, I have used the select() function to make a timeout. But still I have some issue.

So, please tell me, how should I use both functions?

My code is as below:

do{
    rv = select(n, &readfds, NULL, NULL, &tv);

    #ifdef WIFI_DEBUG_PRINT
    ESP_LOGI(Display, "\nselect returns= %d\n",rv);
    #endif

    if (rv > 0) 
    {
        if (FD_ISSET(s, &readfds)) 
        {
            bzero(recv_buf, sizeof(recv_buf));

            read(s, recv_buf, sizeof(recv_buf)-1);

            strcat(response_buffer,recv_buf);

            printf("\nrecv_buf= %s\n",recv_buf);
        }
    }

    _delay_ms_kt(100);  //https://esp32.com/viewtopic.php?f=2&t=809&p=10191&hilit=esp_task_wdt_feed#p10191
                        //see above link to understand reason to put delay here.
                        //https://github.com/espressif/arduino-esp32/issues/595
                        //same.....
}while(rv>0);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
kishan
  • 47
  • 4
  • when my program has working properly,debug print is as below: – kishan Dec 29 '17 at 11:42
  • 1
    `select()` modifies the parameters you pass to it. You need to reset `readfds` and `tv` on each loop iteration. Also, you are not checking the return value of `read()` for error before using `recv_buf`. – Remy Lebeau Dec 31 '17 at 04:23

1 Answers1

0

If you're going to have your program block inside select(), then there is no reason to ever have it block inside read(). Given that, you can avoid any chance of read() ever blocking by setting your socket(s) to non-blocking mode.

That, plus fixing your usage of select() (as suggested by RemyLebeau in his comment) should get you the behavior you want.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234