Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Testing if a file is a terminal?



David Korn has weighed in on this with respect to ksh.

Here is code along he lines he has suggested (my formatting and other
small changes which may have introduced bugs):

#
# Return 1 if $1 is a tty else 0.
#
function _Dbg_is_tty {
    (( $# != 1 )) && return 1
    [[ ! -r $1 ]] || [[ ! -w $1 ]] && return 1
    typeset -i fd
    typeset -i r=1
    # Code courtesy of David Korn:
    {
	if exec {fd}< $1 ; then
	    if [[ -t $fd  ]] ; then
		r=0
		exec {fd}<&-
	    fi
	fi;
    } 2> /dev/null

    return $r
}

An advantage to this is that it's portable across zsh and ksh and if
one removes the {fd} also bash.
(Chet may eventually add  {fd}.)

David Korn also writes:

The -t test checks for more than the major device number.  There might
be several devices that emulate a terminal, ptys, ttys, modems,
consoles. The -t test checks whether tcgetattr() can be called with
this file descriptor on the file.

A disadvantage: if a FIFO is passed, the -t test could have a slight
side effect. If you passed the name of a FIFO that hadn't previously
been opened,  the opening and closing it could have a side effect
since the open will cause the other end of the FIFO to unblock.
Therefore it might make sense to screen these out before the a -t
test.

As before, I welcome comments and thoughts on this and where zsh
differs from ksh with respect to the above code.

Thanks again.

On Tue, Dec 9, 2008 at 11:47 AM, Rocky Bernstein
<rocky.bernstein@xxxxxxxxx> wrote:
> First, many thanks to Peter and Stéphane for the very informative
> answers on terminal redirection.
>
> Before allowing a terminal to be set, the zshdb debugger uses this test:
>
>    [[ -r "$1" && -w "$1" ]] && return 0 # Ok
>
> $1 is a string --  the device name (e.g. /dev/pts/1) -- not a file descriptor.
>
> But is this really the best one can do? I suppose on could also add a
> test if the device is a character device but I just wonder if there
> isn't a better way.
>
> isatty()  works on a file descriptor, but we don't have that yet. I
> suppose one could try to open that and then test but then care needs
> to be made to use that opened file descriptor and not say close and
> reopen that.
>
> Any other thoughts or suggestions?
>
> Thanks again.
>



Messages sorted by: Reverse Date, Date, Thread, Author