0

I am writing a code send the output of a terminal command over a socket in C. I have tried using select for asynchronous reading and avoid blocking the event-loop, but I wasn't successful.

How can I change this code to make the file stream IO non-blocking?

int maxfdpl;
fd_set rset;
char sendline[100], recvline[100], my_msg[100];
FILE *in;
char str[30]="ping 192.168.26.219";
if(!(in = popen(str, "r"))){
   return EXIT_FAILURE;
}
FD_ZERO(&rset);
FD_SET(fileno(in), &rset);
maxfdpl =fileno(in) + 1;
select(maxfdpl, &rset, NULL, NULL, NULL);
while(1) {
      if (FD_ISSET(fileno(in), &rset)) {
         if (fgets(sendline, 100, in)) {
            send_over_socket(sendline);
         }
      }
}

How can I remove the while loop (which is blocking the event-loop) and replace the code with a non-blocking IO operation?

orezvani
  • 3,595
  • 8
  • 43
  • 57

1 Answers1

0
int blockFD(int fd, int blocking)
{
    /* Save the current flags */
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1)
        return 0;

    if (blocking)
        flags &= ~O_NONBLOCK;
    else
        flags |= O_NONBLOCK;

    return fcntl(fd, F_SETFL, flags) != -1;
}

Returns 0 if failed.

Devolus
  • 21,661
  • 13
  • 66
  • 113
  • sorry, but how can I integrate my code with yours? My code is still in the event loop, can you please help me re-write my code? – orezvani May 29 '13 at 13:48
  • Can you explain this code a little bit? still I don't know how to use it – orezvani May 30 '13 at 07:09
  • Considering that you are now two years a member and contributed nothing I'm sure you can manage on your own. After all, the code is pretty selfexplanatory. – Devolus May 30 '13 at 07:30
  • I know that it changes the file descriptor to non-blocking, but how can I capture the event? P.S. I was a two year member but I have been involved in many other things: java, javascript, nodejs, ... – orezvani May 30 '13 at 07:34
  • I mean, instead of a while I should write a listener, or something that will be called whenever the file has a new line to show. Would you help me with that? or refer me to a sample – orezvani May 30 '13 at 07:36
  • You must use (p)select/poll to wait for the events. then you can simply check if data is available, or to be more precice, if a read or write would not block and otherwise you can continue with your regular code. – Devolus May 30 '13 at 07:43
  • I called the function blockFD(fileno(in), 0) and then used select(..) as in my code, I removed the while loop and replaced it with if(read(...)) but it runs only once! – orezvani May 30 '13 at 10:12