getpty.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini getpty implementation for busybox
  4. * Bjorn Wesen, Axis Communications AB (bjornw@axis.com)
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  7. */
  8. #include "libbb.h"
  9. #define DEBUG 0
  10. int FAST_FUNC xgetpty(char *line)
  11. {
  12. int p;
  13. #if ENABLE_FEATURE_DEVPTS
  14. p = open("/dev/ptmx", O_RDWR);
  15. if (p > 0) {
  16. grantpt(p); /* chmod+chown corresponding slave pty */
  17. unlockpt(p); /* (what does this do?) */
  18. #if 0 /* if ptsname_r is not available... */
  19. const char *name;
  20. name = ptsname(p); /* find out the name of slave pty */
  21. if (!name) {
  22. bb_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
  23. }
  24. safe_strncpy(line, name, GETPTY_BUFSIZE);
  25. #else
  26. /* find out the name of slave pty */
  27. if (ptsname_r(p, line, GETPTY_BUFSIZE-1) != 0) {
  28. bb_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
  29. }
  30. line[GETPTY_BUFSIZE-1] = '\0';
  31. #endif
  32. return p;
  33. }
  34. #else
  35. struct stat stb;
  36. int i;
  37. int j;
  38. strcpy(line, "/dev/ptyXX");
  39. for (i = 0; i < 16; i++) {
  40. line[8] = "pqrstuvwxyzabcde"[i];
  41. line[9] = '0';
  42. if (stat(line, &stb) < 0) {
  43. continue;
  44. }
  45. for (j = 0; j < 16; j++) {
  46. line[9] = j < 10 ? j + '0' : j - 10 + 'a';
  47. if (DEBUG)
  48. fprintf(stderr, "Trying to open device: %s\n", line);
  49. p = open(line, O_RDWR | O_NOCTTY);
  50. if (p >= 0) {
  51. line[5] = 't';
  52. return p;
  53. }
  54. }
  55. }
  56. #endif /* FEATURE_DEVPTS */
  57. bb_error_msg_and_die("can't find free pty");
  58. }