getpt.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Copyright (C) 1998-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Zack Weinberg <zack@rabi.phys.columbia.edu>, 1998.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <string.h>
  18. #include <unistd.h>
  19. /* Prefix for master pseudo terminal nodes. */
  20. #define _PATH_PTY "/dev/pty"
  21. /* Letters indicating a series of pseudo terminals. */
  22. #ifndef PTYNAME1
  23. #define PTYNAME1 "pqrsPQRS"
  24. #endif
  25. const char __libc_ptyname1[] attribute_hidden = PTYNAME1;
  26. /* Letters indicating the position within a series. */
  27. #ifndef PTYNAME2
  28. #define PTYNAME2 "0123456789abcdefghijklmnopqrstuv";
  29. #endif
  30. const char __libc_ptyname2[] attribute_hidden = PTYNAME2;
  31. /* Open a master pseudo terminal and return its file descriptor. */
  32. int
  33. __getpt (void)
  34. {
  35. char buf[sizeof (_PATH_PTY) + 2];
  36. const char *p, *q;
  37. char *s;
  38. s = __mempcpy (buf, _PATH_PTY, sizeof (_PATH_PTY) - 1);
  39. /* s[0] and s[1] will be filled in the loop. */
  40. s[2] = '\0';
  41. for (p = __libc_ptyname1; *p != '\0'; ++p)
  42. {
  43. s[0] = *p;
  44. for (q = __libc_ptyname2; *q != '\0'; ++q)
  45. {
  46. int fd;
  47. s[1] = *q;
  48. fd = __open (buf, O_RDWR);
  49. if (fd != -1)
  50. return fd;
  51. if (errno == ENOENT)
  52. return -1;
  53. }
  54. }
  55. __set_errno (ENOENT);
  56. return -1;
  57. }
  58. #undef __getpt
  59. weak_alias (__getpt, getpt)
  60. #ifndef HAVE_POSIX_OPENPT
  61. /* We cannot define posix_openpt in general for BSD systems. */
  62. int
  63. __posix_openpt (int oflag)
  64. {
  65. __set_errno (ENOSYS);
  66. return -1;
  67. }
  68. weak_alias (__posix_openpt, posix_openpt)
  69. stub_warning (posix_openpt)
  70. #endif