forkpty-sunos.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (c) 2008 Nicholas Marriott <nicm@users.sourceforge.net>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
  13. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  14. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include <sys/types.h>
  17. #include <sys/ioctl.h>
  18. #include <fcntl.h>
  19. #include <stdlib.h>
  20. #include <strings.h>
  21. #include <stropts.h>
  22. #include <unistd.h>
  23. #ifndef TTY_NAME_MAX
  24. #define TTY_NAME_MAX TTYNAME_MAX
  25. #endif
  26. pid_t forkpty(int *master, char *name, struct termios *tio, struct winsize *ws)
  27. {
  28. int slave;
  29. char *path;
  30. pid_t pid;
  31. if ((*master = open("/dev/ptmx", O_RDWR|O_NOCTTY)) == -1)
  32. return -1;
  33. if (grantpt(*master) != 0)
  34. goto out;
  35. if (unlockpt(*master) != 0)
  36. goto out;
  37. if ((path = ptsname(*master)) == NULL)
  38. goto out;
  39. if (name != NULL)
  40. strlcpy(name, path, TTY_NAME_MAX);
  41. if ((slave = open(path, O_RDWR|O_NOCTTY)) == -1)
  42. goto out;
  43. switch (pid = fork()) {
  44. case -1:
  45. goto out;
  46. case 0:
  47. close(*master);
  48. setsid();
  49. #ifdef TIOCSCTTY
  50. if (ioctl(slave, TIOCSCTTY, NULL) == -1)
  51. return -1;
  52. #endif
  53. if (ioctl(slave, I_PUSH, "ptem") == -1)
  54. return -1;
  55. if (ioctl(slave, I_PUSH, "ldterm") == -1)
  56. return -1;
  57. if (tio != NULL && tcsetattr(slave, TCSAFLUSH, tio) == -1)
  58. return -1;
  59. if (ioctl(slave, TIOCSWINSZ, ws) == -1)
  60. return -1;
  61. dup2(slave, 0);
  62. dup2(slave, 1);
  63. dup2(slave, 2);
  64. if (slave > 2)
  65. close(slave);
  66. return 0;
  67. }
  68. close(slave);
  69. return pid;
  70. out:
  71. if (*master != -1)
  72. close(*master);
  73. if (slave != -1)
  74. close(slave);
  75. return -1;
  76. }