Guest User

unix-pty-select-emu

a guest
Jun 4th, 2021
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <sys/select.h>
  2. #include <sys/time.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <sys/fcntl.h>
  6. #include <unistd.h>
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include <pty.h>
  11.  
  12.  
  13. #define BUFFSIZE 8
  14.  
  15. int main()
  16. {
  17.     fd_set rfds;
  18.     fd_set wfds;
  19.     fd_set efds;
  20.     struct timeval tv;
  21.     int retval;
  22.  
  23.     char rbuf[BUFFSIZE] = {0};
  24.     int bytes = 0;
  25.  
  26.     const char *msg = "hello world\n";
  27.     const unsigned msg_size = strlen(msg);
  28.  
  29.     int amaster;
  30.     int aslave;
  31.     char filename[512];
  32.     int rc = openpty(&amaster, &aslave, filename, NULL, NULL);
  33.  
  34.     if (rc < 0) {
  35.         perror("openpty()");
  36.         exit(1);
  37.     }
  38.  
  39.     printf("PTY: %s\n", filename);
  40.     printf("Hit [Enter] when ready: ");
  41.     getchar();
  42.  
  43.     int fd = amaster;
  44.  
  45.     while (1) {
  46.         FD_ZERO(&rfds);
  47.         FD_SET(fd, &rfds);
  48.  
  49.         FD_ZERO(&wfds);
  50.         FD_SET(fd, &wfds);
  51.  
  52.         FD_ZERO(&efds);
  53.         FD_SET(fd, &efds);
  54.  
  55.         tv.tv_sec = 1;
  56.         tv.tv_usec = 0;
  57.  
  58.         retval = select(fd + 1, &rfds, &wfds, &efds, &tv);
  59.  
  60.         if (retval == -1) {
  61.             perror("select()");
  62.         }
  63.         else if (retval) {
  64.             if (FD_ISSET(fd, &efds)) {
  65.                 printf("EXCEPTIONAL STATE:");
  66.                 break;
  67.             }
  68.  
  69.             if (FD_ISSET(fd, &rfds)) {
  70.                 printf("READ: Ready\n");
  71.                 bytes = read(fd, rbuf, BUFFSIZE);
  72.                 printf("READ %d bytes. %s", bytes, rbuf);
  73.                 memset(&rbuf, 0, BUFFSIZE);
  74.                 FD_CLR(fd, &rfds);
  75.             }
  76.  
  77.             if (FD_ISSET(fd, &wfds)) {
  78.                 printf("WRITE: Ready.");
  79.                 bytes = write(fd, msg, msg_size);
  80.                 printf("WRITTEN %d bytes.", bytes);
  81.                 FD_CLR(fd, &wfds);
  82.             }
  83.         }
  84.         else {
  85.             printf("timeout()\n");
  86.             /* bytes = write(fd, msg, msg_size); */
  87.             /* break; */
  88.         }
  89.     }
  90.  
  91.     close(fd);
  92.  
  93.     return 0;
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment