cfor-loopsleepposix-select

Is possible to use nanosleep in a infinite loop with select()?


I have a C program that do recv/send operations from/to socket using a for(;;) loop and a select() to monitor the file descriptor. I need also this program to send a packet every 80msec to a packet, how can I implement this? Maybe I can use a fork() and the child process simply write an ack in one of the file descriptor monitored by the select() every 80msec. Is there better solutions?


Solution

  • When calling select() you can use the timeout argument to limit the selection waiting time.

     struct timeval {
               long    tv_sec;         /* seconds */
               long    tv_usec;        /* microseconds */
           };
    
    int select(int nfds, fd_set *readfds, fd_set *writefds,
                  fd_set *exceptfds, struct timeval *timeout);
    

    It is rather easy to limit the timeout to 80msec and send the required packet.