1570af302Sopenharmony_ci#include <stdlib.h>
2570af302Sopenharmony_ci#include <fcntl.h>
3570af302Sopenharmony_ci#include <unistd.h>
4570af302Sopenharmony_ci#include <pty.h>
5570af302Sopenharmony_ci#include <stdio.h>
6570af302Sopenharmony_ci#include <pthread.h>
7570af302Sopenharmony_ci#include <unsupported_api.h>
8570af302Sopenharmony_ci
9570af302Sopenharmony_ci/* Nonstandard, but vastly superior to the standard functions */
10570af302Sopenharmony_ci
11570af302Sopenharmony_ciint openpty(int *pm, int *ps, char *name, const struct termios *tio, const struct winsize *ws)
12570af302Sopenharmony_ci{
13570af302Sopenharmony_ci	int m, s, n=0, cs;
14570af302Sopenharmony_ci	char buf[20];
15570af302Sopenharmony_ci
16570af302Sopenharmony_ci	UNSUPPORTED_API_VOID(LITEOS_A);
17570af302Sopenharmony_ci	m = open("/dev/ptmx", O_RDWR|O_NOCTTY);
18570af302Sopenharmony_ci	if (m < 0) return -1;
19570af302Sopenharmony_ci
20570af302Sopenharmony_ci	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
21570af302Sopenharmony_ci
22570af302Sopenharmony_ci	if (ioctl(m, TIOCSPTLCK, &n) || ioctl (m, TIOCGPTN, &n))
23570af302Sopenharmony_ci		goto fail;
24570af302Sopenharmony_ci
25570af302Sopenharmony_ci	if (!name) name = buf;
26570af302Sopenharmony_ci	snprintf(name, sizeof buf, "/dev/pts/%d", n);
27570af302Sopenharmony_ci	if ((s = open(name, O_RDWR|O_NOCTTY)) < 0)
28570af302Sopenharmony_ci		goto fail;
29570af302Sopenharmony_ci
30570af302Sopenharmony_ci	if (tio) tcsetattr(s, TCSANOW, tio);
31570af302Sopenharmony_ci	if (ws) ioctl(s, TIOCSWINSZ, ws);
32570af302Sopenharmony_ci
33570af302Sopenharmony_ci	*pm = m;
34570af302Sopenharmony_ci	*ps = s;
35570af302Sopenharmony_ci
36570af302Sopenharmony_ci	pthread_setcancelstate(cs, 0);
37570af302Sopenharmony_ci	return 0;
38570af302Sopenharmony_cifail:
39570af302Sopenharmony_ci	close(m);
40570af302Sopenharmony_ci	pthread_setcancelstate(cs, 0);
41570af302Sopenharmony_ci	return -1;
42570af302Sopenharmony_ci}
43