openpty.c 899 字节
Newer Older
R
Rich Felker 已提交
1 2 3 4 5
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <pty.h>
#include <stdio.h>
6
#include <pthread.h>
W
w00349915 已提交
7
#include <unsupported_api.h>
R
Rich Felker 已提交
8 9 10

/* Nonstandard, but vastly superior to the standard functions */

11
int openpty(int *pm, int *ps, char *name, const struct termios *tio, const struct winsize *ws)
R
Rich Felker 已提交
12
{
13
	int m, s, n=0, cs;
R
Rich Felker 已提交
14 15
	char buf[20];

W
w00349915 已提交
16
	unsupported_api(__FUNCTION__);
17 18
	m = open("/dev/ptmx", O_RDWR|O_NOCTTY);
	if (m < 0) return -1;
R
Rich Felker 已提交
19

20 21 22 23
	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);

	if (ioctl(m, TIOCSPTLCK, &n) || ioctl (m, TIOCGPTN, &n))
		goto fail;
R
Rich Felker 已提交
24 25 26

	if (!name) name = buf;
	snprintf(name, sizeof buf, "/dev/pts/%d", n);
27 28
	if ((s = open(name, O_RDWR|O_NOCTTY)) < 0)
		goto fail;
R
Rich Felker 已提交
29

30 31
	if (tio) tcsetattr(s, TCSANOW, tio);
	if (ws) ioctl(s, TIOCSWINSZ, ws);
R
Rich Felker 已提交
32

33 34
	*pm = m;
	*ps = s;
35 36

	pthread_setcancelstate(cs, 0);
R
Rich Felker 已提交
37
	return 0;
38 39 40 41
fail:
	close(m);
	pthread_setcancelstate(cs, 0);
	return -1;
R
Rich Felker 已提交
42
}