SHARE
TWEET

Untitled

a guest Jan 19th, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. select() and pselect() allow a program to monitor multiple file descriptors,
  2. waiting until one or more of the file descriptors become "ready" for some
  3. class of I/O operation
  4.    
  5. #include <sys/types.h>
  6. #include <sys/select.h>
  7.  
  8. #include <unistd.h>
  9.  
  10. #include <stdbool.h>
  11.  
  12. static inline int max(int lhs, int rhs) {
  13.     if(lhs > rhs)
  14.         return lhs;
  15.     else
  16.         return rhs;
  17. }
  18.  
  19. void copy(int from, int to) {
  20.     char buffer[10];
  21.     int readp = 0;
  22.     int writep = 0;
  23.     bool eof = false;
  24.     for(;;) {
  25.         fd_set readfds, writefds;
  26.         FD_ZERO(&readfds);
  27.         FD_ZERO(&writefds);
  28.  
  29.         int ravail, wavail;
  30.         if(readp < writep) {
  31.             ravail = writep - readp - 1;
  32.             wavail = sizeof buffer - writep;
  33.         }
  34.         else {
  35.             ravail = sizeof buffer - readp;
  36.             wavail = readp - writep;
  37.         }
  38.  
  39.         if(!eof && ravail)
  40.             FD_SET(from, &readfds);
  41.         if(wavail)
  42.             FD_SET(to, &writefds);
  43.         else if(eof)
  44.             break;
  45.         int rc = select(max(from,to)+1, &readfds, &writefds, NULL, NULL);
  46.         if(rc == -1)
  47.             break;
  48.         if(FD_ISSET(from, &readfds))
  49.         {
  50.             ssize_t nread = read(from, &buffer[readp], ravail);
  51.             if(nread < 1)
  52.                 eof = true;
  53.             readp = readp + nread;
  54.         }
  55.         if(FD_ISSET(to, &writefds))
  56.         {
  57.             ssize_t nwritten = write(to, &buffer[writep], wavail);
  58.             if(nwritten < 1)
  59.                 break;
  60.             writep = writep + nwritten;
  61.         }
  62.         if(readp == sizeof buffer && writep != 0)
  63.             readp = 0;
  64.         if(writep == sizeof buffer)
  65.             writep = 0;
  66.     }
  67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top