From 7c12435aae39c2bdb5a139390f2dd5b491d35241 Mon Sep 17 00:00:00 2001 From: Bjorn Andersson Date: Wed, 9 May 2018 14:19:25 -0700 Subject: [PATCH] cdba: Gracefully handle stdin not being a tty In the event that cdba is launched from e.g. a cron job stdin won't be a tty and as such we can't modify the termios settings. Signed-off-by: Bjorn Andersson --- cdba.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/cdba.c b/cdba.c index cf7288b..cdcb463 100644 --- a/cdba.c +++ b/cdba.c @@ -47,19 +47,23 @@ #include "circ_buf.h" #include "list.h" -static struct termios orig_tios; static bool quit; static const char *fastboot_file; -static int tty_unbuffer(void) +static struct termios *tty_unbuffer(void) { + static struct termios orig_tios; struct termios tios; int ret; ret = tcgetattr(STDIN_FILENO, &orig_tios); - if (ret < 0) + if (ret < 0) { + /* stdin is not a tty */ + if (errno == ENOTTY) + return NULL; err(1, "unable to retrieve tty tios"); + } memcpy(&tios, &orig_tios, sizeof(struct termios)); tios.c_lflag &= ~(ICANON | ECHO | ISIG); @@ -70,17 +74,20 @@ static int tty_unbuffer(void) if (ret) err(1, "unable to update tty tios"); - return 0; + return &orig_tios; } -static void tty_reset(void) +static void tty_reset(struct termios *orig_tios) { int ret; + if (!orig_tios) + return; + tcflush(STDIN_FILENO, TCIFLUSH); - ret = tcsetattr(STDIN_FILENO, TCSANOW, &orig_tios); + ret = tcsetattr(STDIN_FILENO, TCSANOW, orig_tios); if (ret < 0) - err(1, "unable to reset tty tios"); + warn("unable to reset tty tios"); } static int fork_ssh(const char *host, const char *cmd, int *pipes) @@ -457,6 +464,7 @@ static void usage(void) int main(int argc, char **argv) { + struct termios *orig_tios; struct work *next; struct work *work; struct circ_buf recv_buf = { 0 }; @@ -514,7 +522,7 @@ int main(int argc, char **argv) tv.tv_sec = timeout; tv.tv_usec = 0; - tty_unbuffer(); + orig_tios = tty_unbuffer(); while (!quit) { if (received_power_off) { @@ -610,7 +618,7 @@ int main(int argc, char **argv) wait(NULL); - tty_reset(); + tty_reset(orig_tios); return 0; }