test_pty.c 944 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <fcntl.h>
  2. #include <pty.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <termios.h>
  6. #include <unistd.h>
  7. int main() {
  8. int ptm, pts;
  9. char name[256];
  10. struct termios term;
  11. if (openpty(&ptm, &pts, name, NULL, NULL) == -1) {
  12. perror("openpty");
  13. exit(EXIT_FAILURE);
  14. }
  15. printf("slave name: %s fd: %d\n", name, pts);
  16. tcgetattr(pts, &term);
  17. term.c_lflag &= ~(ICANON | ECHO);
  18. term.c_cc[VMIN] = 1;
  19. term.c_cc[VTIME] = 0;
  20. tcsetattr(pts, TCSANOW, &term);
  21. printf("before print to pty slave\n");
  22. dprintf(pts, "Hello world!\n");
  23. char buf[256];
  24. ssize_t n = read(ptm, buf, sizeof(buf));
  25. if (n > 0) {
  26. printf("read %ld bytes from slave: %.*s", n, (int)n, buf);
  27. }
  28. dprintf(ptm, "hello world from master\n");
  29. char nbuf[256];
  30. ssize_t nn = read(pts, nbuf, sizeof(nbuf));
  31. if (nn > 0) {
  32. printf("read %ld bytes from master: %.*s", nn, (int)nn, nbuf);
  33. }
  34. close(ptm);
  35. close(pts);
  36. return 0;
  37. }