writing to stdin

May 30, 2008 at 3:00am
hi... got a problem how can i write something to stdin...
well about pipes... I really cant get the idea cause...
pipe(), fd[], read(), select(), unistd.h...

I really dont get it... pls help me
May 30, 2008 at 7:34am
I don't think you want to be writing to stdin, thats for incoming data, reading from the keyboard etc, write to stdout and/or stderr. Simple reading from stdin use one of the scanf family, simple writing to stdout/stderr then one of the printf family. Otherwise it depends what you want to do as to how you do it.
May 30, 2008 at 3:13pm
Yes, you can't write to stdin. It is input only.

However, the purpose of a pipe is to attach the stdout of one program to the stdin of another program.

1
2
3
4
5
6
7
8
9
10
// reflect.cpp
#include <iostream>

int main( int argc, char *argv[] )
  {
  std::string s;
  getline( cin, s );
  cout << argv[1] << ": " << s << endl;
  return 0;
  }

If you compile that
$ g++ reflect.cpp -o reflect


you can then use it to test the concept of a pipe:
$ reflect 1 | reflect 2 hello 2: 1: hello $


Let's examine what happened:
1. reflect 1 waited for you to type "hello" (since reflect 1's stdin is the console).
2. reflect 1 printed "1: hello" to its stdout.
3. reflect 1's stdout was piped into reflect 2's stdin
4. reflect 2 read "1: hello"
5. reflect 2 printed "2: 1: hello" to its stdout
6. since reflect 2's stdout was the console, you see "2: 1: hello".

Hope this helps.
Topic archived. No new replies allowed.