sync
[bitrig.git] / bin / ksh / tty.c
blob2751c5a2cf7b349f427a8de1ed472945f79a110f
1 /* $OpenBSD: tty.c,v 1.9 2006/03/14 22:08:01 deraadt Exp $ */
3 #include "sh.h"
4 #include <sys/stat.h>
5 #define EXTERN
6 #include "tty.h"
7 #undef EXTERN
9 /* Initialize tty_fd. Used for saving/reseting tty modes upon
10 * foreground job completion and for setting up tty process group.
12 void
13 tty_init(int init_ttystate)
15 int do_close = 1;
16 int tfd;
18 if (tty_fd >= 0) {
19 close(tty_fd);
20 tty_fd = -1;
22 tty_devtty = 1;
24 if ((tfd = open("/dev/tty", O_RDWR, 0)) < 0) {
25 tty_devtty = 0;
26 warningf(false, "No controlling tty (open /dev/tty: %s)",
27 strerror(errno));
30 if (tfd < 0) {
31 do_close = 0;
32 if (isatty(0))
33 tfd = 0;
34 else if (isatty(2))
35 tfd = 2;
36 else {
37 warningf(false, "Can't find tty file descriptor");
38 return;
41 if ((tty_fd = fcntl(tfd, F_DUPFD, FDBASE)) < 0) {
42 warningf(false, "j_ttyinit: dup of tty fd failed: %s",
43 strerror(errno));
44 } else if (fcntl(tty_fd, F_SETFD, FD_CLOEXEC) < 0) {
45 warningf(false, "j_ttyinit: can't set close-on-exec flag: %s",
46 strerror(errno));
47 close(tty_fd);
48 tty_fd = -1;
49 } else if (init_ttystate)
50 tcgetattr(tty_fd, &tty_state);
51 if (do_close)
52 close(tfd);
55 void
56 tty_close(void)
58 if (tty_fd >= 0) {
59 close(tty_fd);
60 tty_fd = -1;