Subject: [PATCH 1/1] tty: do not provide conflicting information

From: Christian Brauner <[email-masked]>
Date: Wed, 5 Apr 2017 16:44:41 +0200

In case the current file descriptor is a tty but ttyname{_r}() fails to retrieve
the device path tty would falsely report "not a tty" but return EXIT_SUCCESS.
This is confusing. Instead, let's first check whether the fd refers to a tty and
if not report "not a tty" and exit with error. In all other cases, we should
report "is a tty but failed to determine the device path" and exit with success.
This is much clearer. Depending on the platform the user can then decide how to
proceed, e.g. by looking at /proc/self/fd/0 for Linux or somewhere else on other
platforms.

Signed-off-by: Christian Brauner <[email-masked]>
---
 src/tty.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/src/tty.c b/src/tty.c
index c3fdabc85..fb21a995a 100644
--- a/src/tty.c
+++ b/src/tty.c
@@ -79,6 +79,7 @@ main (int argc, char **argv)
 {
   char *tty;
   int optc;
+  int is_tty;
 
   initialize_main (&argc, &argv);
   set_program_name (argv[0]);
@@ -111,14 +112,21 @@ main (int argc, char **argv)
   if (optind < argc)
     error (0, 0, _("extra operand %s"), quote (argv[optind]));
 
+  is_tty = isatty (STDIN_FILENO);
+  if (!is_tty)
+    {
+      puts (_("not a tty"));
+      return EXIT_FAILURE;
+    }
+
   tty = ttyname (STDIN_FILENO);
   if (!silent)
     {
       if (tty)
         puts (tty);
       else
-        puts (_("not a tty"));
+        puts (_("is a tty but failed to determine the device path"));
     }
 
-  return isatty (STDIN_FILENO) ? EXIT_SUCCESS : EXIT_FAILURE;
+  return EXIT_SUCCESS;
 }
-- 
2.11.0