nneonneo
nneonneo

Reputation: 179422

How can a program read console input after input redirection?

I've always found the command-line mysql utility to be a bit surprising, because you can do this:

gzcat dumpfile.sql.gz | mysql -u <user> -p <options>

and mysql will prompt you for a password. Now, stdin in mysql is redirected -- one would expect it to read the password from the dumpfile. Instead, it somehow bypasses stdin and goes straight for the terminal. ssh does the same kind of thing.

I suspect this is some sort of /dev/tty or /dev/pty magic, but I'd appreciate a proper explanation for this apparent magic :) (and why these programs can do it on any platform, even Windows).

Upvotes: 1

Views: 428

Answers (1)

ruakh
ruakh

Reputation: 183321

As you surmise, it is using /dev/tty, which is specified this way:

In each process, [/dev/tty is] a synonym for the controlling terminal associated with the process group of that process, if any. It is useful for programs or shell procedures that wish to be sure of writing messages to or reading data from the terminal no matter how output has been redirected. It can also be used for programs that demand the name of a file for output, when typed output is desired and it is tiresome to find out what terminal is currently in use.

No real "magic" beyond that.

[link]

Upvotes: 3

Related Questions