forkpty.c 753 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include <pty.h>
  2. #include <unistd.h>
  3. #include <sys/ioctl.h>
  4. #include <fcntl.h>
  5. int forkpty(int *m, char *name, const struct termios *tio, const struct winsize *ws)
  6. {
  7. int s, t, i, istmp[3]={0};
  8. pid_t pid;
  9. if (openpty(m, &s, name, tio, ws) < 0) return -1;
  10. /* Ensure before forking that we don't exceed fd limit */
  11. for (i=0; i<3; i++) {
  12. if (fcntl(i, F_GETFL) < 0) {
  13. t = fcntl(s, F_DUPFD, i);
  14. if (t<0) break;
  15. else if (t!=i) close(t);
  16. else istmp[i] = 1;
  17. }
  18. }
  19. pid = i==3 ? fork() : -1;
  20. if (!pid) {
  21. close(*m);
  22. setsid();
  23. ioctl(s, TIOCSCTTY, (char *)0);
  24. dup2(s, 0);
  25. dup2(s, 1);
  26. dup2(s, 2);
  27. if (s>2) close(s);
  28. return 0;
  29. }
  30. for (i=0; i<3; i++)
  31. if (istmp[i]) close(i);
  32. close(s);
  33. if (pid < 0) close(*m);
  34. return pid;
  35. }