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