How detect assigned terminal device for interactive work How detect assigned terminal device for interactive work unix unix

How detect assigned terminal device for interactive work


What less does in this situation is fall back to fd 2 (stderr). If stderr has been redirected away from the tty, it gives up on trying to get keyboard input, and just prints the whole input stream without paging.

The design of su doesn't allow for anything better. The new user is running a command on a tty owned by the original user, and that unpleasant fact can't be entirely hidden.

Here's a nice substitute for su that doesn't have this problem:

ssh -t localhost -l username sh -c 'command'

It has a little more overhead, of course.


On the end I used pattern that I found in less pager, but modified for using with ncurses:

First I try to reopen stdin to some tty related device:

if (!isatty(fileno(stdin))){    if (freopen("/dev/tty", "r", stdin) != NULL)        noatty = false;    /* when tty is not accessible, try to get tty from stdout */     else if (freopen(ttyname(fileno(stdout)), "r", stdin) != NULL)        noatty = false;    else    {        /*         * just ensure stderr is joined to tty, usually when reopen         * of fileno(stdout) fails - probably due permissions.         */        if (!isatty(fileno(stderr)))        {            fprintf(stderr, "missing a access to terminal device\n");            exit(1);        }        noatty = true;        fclose(stdin);    }}                   else    noatty = false;

When I have not tty and cannot to use stdin, then I am using newterm functions, that allows to specify input stream:

if (noatty)    /* use stderr like stdin. This is fallback solution used by less */    newterm(termname(), stdout, stderr);else    /* stdin is joined with tty, then use usual initialization */    initscr();