1

Possible Duplicate:
Writing to stdin and reading from stdout (UNIX/LINUX/C Programming)

I have a simple question regarding stdio of linux system.

what happens if a program writes to stdin? or reads from stdout, stderr...?

I want to know the details from operating system's view. thank you in advance

Community
  • 1
  • 1
daehee
  • 5,047
  • 7
  • 44
  • 70
  • Looking for this http://stackoverflow.com/questions/3385201/confused-about-stdin-stdout-and-stderr – Satish Dec 19 '12 at 19:44

1 Answers1

1

stdio streams on Linux are associated with file descriptors, as are all files and streams on Linux and UNIX. Initially, those file descriptors are associated with a tty, which is really just a file (of sorts). Initially, the file descriptors for those are mapped to those TTYs. The user, or your program can also remap them. For example, I could remap stderr to a log file, or stdin to some pre-baked input.

Linuxios
  • 34,849
  • 13
  • 91
  • 116
  • Stdio streams are not associated with `tty`s but with file descriptors. – Basile Starynkevitch Dec 19 '12 at 18:31
  • @BasileStarynkevitch; And those file descriptors are opened to TTYs. Why the downvote? – Linuxios Dec 19 '12 at 18:34
  • @BasileStarynkevitch: Fixed. Would you revoke the downvote? – Linuxios Dec 19 '12 at 18:35
  • @Linuxios The file descriptors are arbitrary file descriptors. Nothing constrains them to be initially bound to tty. In fact, this is not the case when a process is reading from or writing to a pipe (think shell), or the process is run by another process, ... They may even be sockets. In fact, the only thing that is sure about them is that they correspond to file descriptors 0, 1 and 2 respectively in the POSIX environment. – Sylvain Defresne Dec 19 '12 at 19:02
  • @SylvainDefresne: Nothing contrains them, that is just their default if not set otherwise. – Linuxios Dec 19 '12 at 19:05
  • @Linuxios That is wrong, by default they are inherited from their parent process. They can be re-routed by the process itself (using `dup2`), but they don't default to `tty`. – Sylvain Defresne Dec 19 '12 at 19:08
  • @SylvainDefresne: Let's say on a new process, they default. But I completely agree with you thanks for info. – Linuxios Dec 19 '12 at 19:11
  • No, on a new process they don't default to `tty`. The only situation where they are probably going to be bound to `tty` is when their parent is `/sbin/getty` (or another program whose role is to connect its child to a `tty`, like `xterm`). When running in a terminal, it happens that the shell is connected to `tty` and since process launched by the shell inherit the `stdin`, `stdout` and `stderr` (well, all file descriptor in fact) from their parent, they are also connected to the `tty`. – Sylvain Defresne Dec 19 '12 at 19:20