this is not working and I don't know why
Because you are using dup()
. To redirect the standard input of the child process to the pipe, the correct system call to use is dup2()
case 0:
close( fd[1] );
dup2( fd[0], 0 ); // this "dup"s the read-end of the pipe onto STDIN
close( fd[0] );
Note that you don't need the dup()
call at all in the parent code branch. Just write to the write-end of the pipe:
write( fd[1], "Hello World\n", 12 );
However, if you want to use execvp in the parent branch also, to launch another program with its standard output redirected, then you would have to use dup2()
here also:
dup2( fd[1], 1 ); // this "dup"s the write-end of the pipe onto STDOUT
close( fd[1] );
Read the manpage for dup2
for details.
Also, another problem with your code is the use of execvp with argv
as the argument list. This will cause programs like rev
and wc
to receive the entire command line of the parent program and thus find an argument to process rather than read from standard input. You probably want
execvp( argv[1], &argv[1] );