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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.