busybox/miscutils/ttysize.c
<<
>>
Prefs
   1/* vi: set sw=4 ts=4: */
   2/*
   3 * Replacement for "stty size", which is awkward for shell script use.
   4 * - Allows to request width, height, or both, in any order.
   5 * - Does not complain on error, but returns width 80, height 24.
   6 * - Size: less than 200 bytes
   7 *
   8 * Copyright (C) 2007 by Denys Vlasenko <vda.linux@googlemail.com>
   9 *
  10 * Licensed under GPLv2, see file LICENSE in this source tree.
  11 */
  12//config:config TTYSIZE
  13//config:       bool "ttysize (432 bytes)"
  14//config:       default y
  15//config:       help
  16//config:       A replacement for "stty size". Unlike stty, can report only width,
  17//config:       only height, or both, in any order. It also does not complain on
  18//config:       error, but returns default 80x24.
  19//config:       Usage in shell scripts: width=`ttysize w`.
  20
  21//applet:IF_TTYSIZE(APPLET_NOFORK(ttysize, ttysize, BB_DIR_USR_BIN, BB_SUID_DROP, ttysize))
  22
  23//kbuild:lib-$(CONFIG_TTYSIZE) += ttysize.o
  24
  25//usage:#define ttysize_trivial_usage
  26//usage:       "[w] [h]"
  27//usage:#define ttysize_full_usage "\n\n"
  28//usage:       "Print dimensions of stdin tty, or 80x24"
  29
  30#include "libbb.h"
  31
  32int ttysize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  33int ttysize_main(int argc UNUSED_PARAM, char **argv)
  34{
  35        unsigned w, h;
  36        struct winsize wsz;
  37
  38        w = 80;
  39        h = 24;
  40        if (ioctl(0, TIOCGWINSZ, &wsz) == 0
  41         || ioctl(1, TIOCGWINSZ, &wsz) == 0
  42         || ioctl(2, TIOCGWINSZ, &wsz) == 0
  43        ) {
  44                w = wsz.ws_col;
  45                h = wsz.ws_row;
  46        }
  47
  48        if (!argv[1]) {
  49                printf("%u %u", w, h);
  50        } else {
  51                const char *fmt, *arg;
  52
  53                fmt = "%u %u" + 3; /* "%u" */
  54                while ((arg = *++argv) != NULL) {
  55                        char c = arg[0];
  56                        if (c == 'w')
  57                                printf(fmt, w);
  58                        if (c == 'h')
  59                                printf(fmt, h);
  60                        fmt = "%u %u" + 2; /* " %u" */
  61                }
  62        }
  63        bb_putchar('\n');
  64        return 0;
  65}
  66