]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
terminal-util: introduce isatty_safe that rejects EBADF
authorMike Yuan <me@yhndnzj.com>
Fri, 22 Dec 2023 09:59:39 +0000 (17:59 +0800)
committerMike Yuan <me@yhndnzj.com>
Fri, 22 Dec 2023 15:06:48 +0000 (23:06 +0800)
src/basic/terminal-util.c
src/basic/terminal-util.h

index 89823ab79537093273b9da4a25451d5897179b47..c6ced3f7c10c3c90be3f3fce89273d11494781c0 100644 (file)
@@ -54,6 +54,18 @@ static volatile int cached_on_dev_null = -1;
 static volatile int cached_color_mode = _COLOR_INVALID;
 static volatile int cached_underline_enabled = -1;
 
+bool isatty_safe(int fd) {
+        assert(fd >= 0);
+
+        if (isatty(fd))
+                return true;
+
+        /* Be resilient if we're working on stdio, since they're set up by parent process. */
+        assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
+
+        return false;
+}
+
 int chvt(int vt) {
         _cleanup_close_ int fd = -EBADF;
 
index 1ec057c2dd5be75efb345df23968b04ca22a10f7..ee60ff4840c3c7902eaaf5c7f8de7be99dced792 100644 (file)
@@ -86,6 +86,8 @@
 /* Set cursor to top left corner and clear screen */
 #define ANSI_HOME_CLEAR "\x1B[H\x1B[2J"
 
+bool isatty_safe(int fd);
+
 int reset_terminal_fd(int fd, bool switch_to_text);
 int reset_terminal(const char *name);
 int set_terminal_cursor_position(int fd, unsigned int row, unsigned int column);