b6962e131c8e6fe935d01b48a48f1d7fddf6d890
[musl] / src / misc / openpty.c
1 #include <stdlib.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 #include <pty.h>
5 #include <stdio.h>
6
7 /* Nonstandard, but vastly superior to the standard functions */
8
9 int openpty(int *pm, int *ps, char *name, const struct termios *tio, const struct winsize *ws)
10 {
11         int m, s, n=0;
12         char buf[20];
13
14         m = open("/dev/ptmx", O_RDWR|O_NOCTTY);
15         if (m < 0) return -1;
16
17         if (ioctl(m, TIOCSPTLCK, &n) || ioctl (m, TIOCGPTN, &n)) {
18                 close(m);
19                 return -1;
20         }
21
22         if (!name) name = buf;
23         snprintf(name, sizeof buf, "/dev/pts/%d", n);
24         if ((s = open(name, O_RDWR|O_NOCTTY)) < 0) {
25                 close(m);
26                 return -1;
27         }
28
29         if (tio) tcsetattr(s, TCSANOW, tio);
30         if (ws) ioctl(s, TIOCSWINSZ, ws);
31
32         *pm = m;
33         *ps = s;
34         return 0;
35 }