tags:

views:

116

answers:

2

I'd like to write a program which reads user input only from tty, instead of redirected stdin pipes, like passwd and ssh do. Is there any approach?

Many thanks

+2  A: 

You should try opening /dev/tty directly. That's the only way I know for sure that you can bypass the stdin redirection.

/dev/tty is usually a symbolic link to your actual tty device, which may be /dev/console or /dev/tty24 or pretty much anything you want, depending on the weird and wonderful way your system may be set up. The tty command should be able to tell you which one it is (as will listing the symbolic link itself with ls -al /dev/tty).

But as long as you open dev/tty for input, it should get the input from your terminal rather than the standard input stream, which may have been redirected.

paxdiablo
/dev/tty is not really a symbolic link, but it's a real device file which the kernel uses to mean the controlling terminal for the process which is trying to use it. The controlling terminal is what you'd want for things like passwords and less keystrokes.
nategoose
Maybe that's a Linux thing, @nategoose. I seem to remember it showing up as "tty -> ttyd9" (a symbolic link) in some UNIXes and indeed using a nasty trick like temorarily replacing /dev/tty with a real file so that programs using the fopen(/dev/tty) method that I suggest would instead read my file (for automation and, of course, needed root privs).
paxdiablo
A: 

You can try isatty(man 3 isatty) in conjunction with fileno():

   #include <unistd.h>

   int isatty(int fd);