tty.c revision 1.9
1/* $OpenBSD: tty.c,v 1.9 2006/03/14 22:08:01 deraadt 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 tty_devtty = 0; 26 warningf(false, "No controlling tty (open /dev/tty: %s)", 27 strerror(errno)); 28 } 29 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; 39 } 40 } 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); 53} 54 55void 56tty_close(void) 57{ 58 if (tty_fd >= 0) { 59 close(tty_fd); 60 tty_fd = -1; 61 } 62} 63