Writing to stdin and reading from stdout (UNIX/LINUX/C Programming) Writing to stdin and reading from stdout (UNIX/LINUX/C Programming) unix unix

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


Attempting to write on a file marked readonly or vice-versa would cause write and read to return -1, and fail. In this specific case, stdin and stdout are actually the same file. In essence, before your program executes (if you don't do any redirection) the shell goes:

  if(!fork()){       <close all fd's>       int fd = open("/dev/tty1", O_RDWR);       dup(fd);       dup(fd);       execvp("name", argv);  }

So, stdin, out, and err are all duplicates of the same file descriptor, opened for reading and writing.


read(STDIN_FILENO, message, 20); write(STDOUT_FILENO, message, 20);

Should work. Note - stdout my be a different place from stdin (even on the command line). You can feed output from another process as stdin into you process, or arrange the stdin/stdout to be files.

fprintf/fgets have a buffer - thus reducing the number of system calls.


Best guess - stdin points to where the input is coming from, your terminal and stdout points to where output should be going, your terminal. Since they both point to the same place they are interchangeable(in this case)?