tty.c revision 1.7
1/*	$OpenBSD: tty.c,v 1.7 2004/12/22 17:14:34 millert Exp $	*/
2
3#include "sh.h"
4#include <sys/stat.h>
5#define EXTERN
6#include "tty.h"
7#undef EXTERN
8
9/* Initialize tty_fd.  Used for saving/reseting tty modes upon
10 * foreground job completion and for setting up tty process group.
11 */
12void
13tty_init(int init_ttystate)
14{
15	int	do_close = 1;
16	int	tfd;
17
18	if (tty_fd >= 0) {
19		close(tty_fd);
20		tty_fd = -1;
21	}
22	tty_devtty = 1;
23
24	if ((tfd = open("/dev/tty", O_RDWR, 0)) < 0) {
25
26		if (tfd < 0) {
27			tty_devtty = 0;
28			warningf(false,
29				"No controlling tty (open /dev/tty: %s)",
30				strerror(errno));
31		}
32	}
33
34	if (tfd < 0) {
35		do_close = 0;
36		if (isatty(0))
37			tfd = 0;
38		else if (isatty(2))
39			tfd = 2;
40		else {
41			warningf(false, "Can't find tty file descriptor");
42			return;
43		}
44	}
45	if ((tty_fd = fcntl(tfd, F_DUPFD, FDBASE)) < 0) {
46		warningf(false, "j_ttyinit: dup of tty fd failed: %s",
47			strerror(errno));
48	} else if (fcntl(tty_fd, F_SETFD, FD_CLOEXEC) < 0) {
49		warningf(false, "j_ttyinit: can't set close-on-exec flag: %s",
50			strerror(errno));
51		close(tty_fd);
52		tty_fd = -1;
53	} else if (init_ttystate)
54		tcgetattr(tty_fd, &tty_state);
55	if (do_close)
56		close(tfd);
57}
58
59void
60tty_close(void)
61{
62	if (tty_fd >= 0) {
63		close(tty_fd);
64		tty_fd = -1;
65	}
66}
67