tags:

views:

379

answers:

3

I need to run a script and have access to the default stdin (terminal input) in my program. I could do ./program "script", opening and parsing the script through the program, but I want to make it POSIX style, accepting input from pipes or from redirection.

I mean, since my program is a parser, I could run ./program, type the script and still use stdin (in a scanf, for example). But I'd like to run ./program < script and still be able to use stdin (in a scanf).

My program is a simplified Pascal interpreter, that's why I need to run read(x) and write(x) in my scripts.

Yes, it's homework (the intepreter), but the doubt just popped up in the brainstorming process.

A: 

If I understand what you're asking, you're asking for the ability to take in interactive input from a user when using file redirection, like the ./program < script bit above.

I don't believe there's a way to do that. A POSIX system will feed the script in via stdin and that's that. No interaction from the user.

It's also worth noting that you don't have to do anything special to realize that. Just treat stdin like you normally would. You don't have to think about whether it's coming in interactively or from a file, which is really quite nice.

Brian Arnold
The final bit, about file redirection I already knew, what I really wanted to know is the file that the current terminal is bound to, just as mark4o stated.
Spidey
+1  A: 

ttyname(0) will return the filename of the current terminal associated with stdin. You can then open that and read from it.

Nick Lewis
Well, I guess you learn something new every day. :) Still, doesn't really seem like something one would want to do often. :)
Brian Arnold
It's not common, but I had to use it to implement the 'more' program for a class last year. Reads input from a file, and outputs it to stdout, but also has to read input from the keyboard to continue scrolling. :)
Nick Lewis
You did a more that accepted piped/redirected input?Btw, ttyname(0) will get stdin to me, but since it were redirected, I won't get the terminal, will I?Maybe I could use the returned string to find out what is stdin...
Spidey
/dev/tty/XXX is the device itself, so opening that will get input from the actual device. stdin is just the *standard* input stream, which is TYPICALLY /dev/tty/XXX, but is changed to the input file when using input redirection.
Nick Lewis
So the 0 on ttyname is not the same 0 as in stdin? It's actually the 0 terminal, which is always the current terminal?
Spidey
+2  A: 

The current controlling terminal can be accessed using /dev/tty, even if stdin has been redirected.

mark4o
Perhaps it is good to add that opening /dev/tty will fail in those cases, where no controlling terminal exists.Two common cases are: process was started through cron or through at. In general, processes started from deamons are themselves daemons and have no controlling terminal.
Ingo