test_pty.c 912 B

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