]> git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/ttyutils.c
lib: try to find tty in get_terminal_name()
[thirdparty/util-linux.git] / lib / ttyutils.c
1 /*
2 * No copyright is claimed. This code is in the public domain; do with
3 * it what you wish.
4 *
5 * Written by Karel Zak <kzak@redhat.com>
6 */
7 #include <ctype.h>
8 #include <unistd.h>
9
10 #include "c.h"
11 #include "ttyutils.h"
12
13 int get_terminal_width(int default_width)
14 {
15 int width = 0;
16
17 #if defined(TIOCGWINSZ)
18 struct winsize w_win;
19 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &w_win) == 0)
20 width = w_win.ws_col;
21 #elif defined(TIOCGSIZE)
22 struct ttysize t_win;
23 if (ioctl (STDOUT_FILENO, TIOCGSIZE, &t_win) == 0)
24 width = t_win.ts_cols;
25 #endif
26
27 if (width <= 0) {
28 const char *cp = getenv("COLUMNS");
29
30 if (cp) {
31 char *end = NULL;
32 long c;
33
34 errno = 0;
35 c = strtol(cp, &end, 10);
36
37 if (errno == 0 && end && *end == '\0' && end > cp &&
38 c > 0 && c <= INT_MAX)
39 width = c;
40 }
41 }
42
43 return width > 0 ? width : default_width;
44 }
45
46 int get_terminal_name(const char **path,
47 const char **name,
48 const char **number)
49 {
50 const char *tty;
51 const char *p;
52 int fd;
53
54
55 if (name)
56 *name = NULL;
57 if (path)
58 *path = NULL;
59 if (number)
60 *number = NULL;
61
62 if (isatty(STDIN_FILENO))
63 fd = STDIN_FILENO;
64 else if (isatty(STDOUT_FILENO))
65 fd = STDOUT_FILENO;
66 else if (isatty(STDERR_FILENO))
67 fd = STDERR_FILENO;
68 else
69 return -1;
70
71 tty = ttyname(fd);
72 if (!tty)
73 return -1;
74 if (path)
75 *path = tty;
76 tty = strncmp(tty, "/dev/", 5) == 0 ? tty + 5 : tty;
77 if (name)
78 *name = tty;
79 if (number) {
80 for (p = tty; p && *p; p++) {
81 if (isdigit(*p)) {
82 *number = p;
83 break;
84 }
85 }
86 }
87 return 0;
88 }
89
90
91 #ifdef TEST_PROGRAM
92 # include <stdlib.h>
93 int main(void)
94 {
95 const char *path, *name, *num;
96
97 if (get_terminal_name(STDERR_FILENO, &path, &name, &num) == 0) {
98 fprintf(stderr, "tty path: %s\n", path);
99 fprintf(stderr, "tty name: %s\n", name);
100 fprintf(stderr, "tty number: %s\n", num);
101 }
102 fprintf(stderr, "tty width: %d\n", get_terminal_width(0));
103
104 return EXIT_SUCCESS;
105 }
106 #endif