I am trying to execute an external program (echo is just for testing, but should work nevertheless). The program takes the first argument and submits it to the second, that requires them over STDIN.
The redirection to the pipe and therefore to STDIN is working perfectly, if you print out the pipe content instead of using exec.
But the program (echo) is not returning anything, the behaviour stays the same. Therefore the STDIN is not redirected, but I don't understand why. Is there a missing parameter in the exec-family I am missing or something?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("parameters do not match");
exit(1);
}
// create two pipes
int downstream[2];
int upstream[2];
pipe(downstream);
pipe(upstream);
// create child
if (fork() == 0)
{
// close not required descriptors
close(upstream[0]);
close(downstream[1]);
// close and duplicate stdin/stdout from pipe
dup2(downstream[0], STDIN_FILENO);
dup2(upstream[1], STDOUT_FILENO);
// exec
// What to do here?
char *args[] = {"echo", NULL};
execvp(args[0], args);
exit(0);
}
// close not required
close(upstream[1]);
close(downstream[0]);
// send second argument to pipe
write(downstream[1], argv[1], strlen(argv[1]));
// read result from pipe
char buffer[100];
read(upstream[0], buffer, 100);
printf("OUTPUT: %s", buffer);
exit(0);
}
echodoes not read from stdin.catinstead.argv[1][strlen(argv[1])] = '\0';