pty.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /* posix */
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <errno.h>
  7. #include <string.h>
  8. #include <fcntl.h>
  9. #include <sys/stat.h>
  10. #include <sys/pty.h>
  11. #include "lib.h"
  12. #include "sys9.h"
  13. #include "dir.h"
  14. /*
  15. * return the name of the slave
  16. */
  17. char*
  18. ptsname(int fd)
  19. {
  20. Dir *d;
  21. static char buf[32];
  22. if((d = _dirfstat(fd)) == nil || strlen(d->name) < 4){
  23. free(d);
  24. _syserrno();
  25. return 0;
  26. }
  27. sprintf(buf, "/dev/ptty%d", atoi(d->name+4));
  28. free(d);
  29. return buf;
  30. }
  31. /*
  32. * return the name of the master
  33. */
  34. char*
  35. ptmname(int fd)
  36. {
  37. Dir *d;
  38. static char buf[32];
  39. if((d = _dirfstat(fd)) == nil || strlen(d->name) < 4){
  40. free(d);
  41. _syserrno();
  42. return 0;
  43. }
  44. sprintf(buf, "/dev/ttym%d", atoi(d->name+4));
  45. return buf;
  46. }
  47. static char ptycl[] = "/dev/ptyclone";
  48. static char fssrv[] = "/srv/ptyfs";
  49. static void
  50. mkserver(void)
  51. {
  52. int fd, i;
  53. char *argv[3];
  54. fd = _OPEN(fssrv, O_RDWR);
  55. if(_MOUNT(fd, -1, "/dev", MAFTER, "") < 0) {
  56. /*
  57. * remove fssrv here, if it exists, to avoid a race
  58. * between the loop in the default case below and the
  59. * new ptyfs removing fssrv when it starts.
  60. * we otherwise might be unlucky enough to open the old
  61. * (hung channel) fssrv before ptyfs removes it and break
  62. * out of the loop with an open fd to a hung channel?
  63. */
  64. _CLOSE(fd);
  65. _REMOVE(fssrv);
  66. switch(_RFORK(RFPROC|RFFDG)) {
  67. case -1:
  68. return;
  69. case 0:
  70. argv[0] = "ptyfs";
  71. argv[1] = 0;
  72. _EXEC("/bin/ape/ptyfs", argv);
  73. _EXITS(0);
  74. default:
  75. for(i = 0; i < 3; i++) {
  76. fd = _OPEN(fssrv, O_RDWR);
  77. if(fd >= 0)
  78. break;
  79. _SLEEP(1000);
  80. }
  81. }
  82. if(fd < 0)
  83. return;
  84. if(_MOUNT(fd, -1, "/dev", MAFTER, "") < 0)
  85. _CLOSE(fd);
  86. }
  87. /* successful _MOUNT closes fd */
  88. }
  89. /*
  90. * allocate a new pty
  91. */
  92. int
  93. _getpty(void)
  94. {
  95. struct stat sb;
  96. if(stat(ptycl, &sb) < 0)
  97. mkserver();
  98. return open(ptycl, O_RDWR);
  99. }