paulsm4, I've saw the example, but I'm still very confusing about it.
Code:
1void piping(char* cmd[], int nr)
2{
3 int i;
4 int thisin;
5 int pid[2];
6
7 thisin = fileno( stdin );// get stdin descriptor
8
9 for ( i=0; i<nr; i++)
10 {
11 pipe( pid );
12
13 if ( fork() == 0 )
14 {
15 dup2( thisin, fileno( stdin ));
16
17 if ( i != (nr-1) )// i isn't the last example
18 dup2( pid[1], fileno ( stdout ));
19
20 close(pid[0]);
21 close(pid[1]);
22
23 execlp ( cmd[i], cmd[i], NULL);
24 }
25 else
26 {
27 dup2( pid[0], thisin);
28
29 close(pid[0]);
30 close(pid[1]);
31 }
32 }
33}
- why line 17 is needed? The last command don't have to write in the stdout?
- Why this example only works to pipes with 3 programs execution? Eg. "ls -la | sort | wc". And doesn't work with 2, 4, 5, ..., n program executions?
I'm really confused about the functioning of the pipes. I've already googled up, read books ("Advanced Programming in Unix environments", and I'm still very mixed up.
I don't have any friend that program C at this level, so I can't get any help from them.