From 689bfc793987950590a6066b91c6f8ca166a5fca Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Wed, 9 Mar 2016 18:28:00 -0800 Subject: [PATCH] Open stdin and stdout to something if they don't arrive open, or bad things happen. --- adsbus/adsbus.c | 2 ++ adsbus/stdinout.c | 15 ++++++++++++++- adsbus/stdinout.h | 1 + 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/adsbus/adsbus.c b/adsbus/adsbus.c index 7c68fc2..1d9b218 100644 --- a/adsbus/adsbus.c +++ b/adsbus/adsbus.c @@ -33,6 +33,8 @@ static void adsbus_opts_add() { } int main(int argc, char *argv[]) { + stdinout_preinit(); + adsbus_opts_add(); opts_init(argc, argv); diff --git a/adsbus/stdinout.c b/adsbus/stdinout.c index 3a9e88e..97af4fe 100644 --- a/adsbus/stdinout.c +++ b/adsbus/stdinout.c @@ -13,10 +13,14 @@ static opts_group stdinout_opts; +static void stdinout_open(int fd, char *path, int flags) { + assert(open(path, flags | O_CLOEXEC | O_NOCTTY) == fd); +} + static void stdinout_reopen(int fd, char *path, int flags) { // Presumes that all fds < fd are open assert(!close(fd)); - assert(open(path, flags | O_CLOEXEC | O_NOCTTY) == fd); + stdinout_open(fd, path, flags); } static bool stdinout_stdin(const char __attribute__((unused)) *arg) { @@ -35,6 +39,15 @@ static bool stdinout_stdout(const char *arg) { return flow_new_send_hello(fd, send_flow, serializer, NULL); } +void stdinout_preinit() { + if (fcntl(STDIN_FILENO, F_GETFD) == -1) { + stdinout_open(STDIN_FILENO, "/dev/null", O_RDONLY); + } + if (fcntl(STDOUT_FILENO, F_GETFD) == -1) { + stdinout_open(STDOUT_FILENO, "/dev/full", O_WRONLY); + } +} + void stdinout_opts_add() { opts_add("stdin", NULL, stdinout_stdin, stdinout_opts); opts_add("stdout", "FORMAT", stdinout_stdout, stdinout_opts); diff --git a/adsbus/stdinout.h b/adsbus/stdinout.h index b741cac..a13f598 100644 --- a/adsbus/stdinout.h +++ b/adsbus/stdinout.h @@ -1,5 +1,6 @@ #pragma once +void stdinout_preinit(void); void stdinout_opts_add(void); void stdinout_init(void); void stdinout_cleanup(void);