I try to pass the stdout of an program in a child process to the stdin in the parents process.
In bash this would look like this:
wget "adress"|less
My code looks like this:
int fd[2];
pid_t child_id;
int status;
char *args[] = {"wget","-O -",argv[1], NULL};
int pipe(int fd[2]);
child_id = fork();
if (child_id == -1)
{
printf ("Fork error\n");
}
if (child_id == 0)
{
close(fd[0]);
int c = dup2(fd[1],1);
execl ("/usr/bin/wget", "wget", "-qO-",argv[1], NULL);
}
else{
waitpid(child_id,&status,0);
close(fd[1]);
int c2 = dup2(fd[0],STDIN_FILENO);
printf("%i\n",c2 ); //debugging
execl ("/usr/bin/less", "less", NULL);
}
Please note that argv[1] should be an webadress.
But when running the program the debug output of the dup2 (int c2 = dup2(fd[0],STDIN_FILENO);
) in the parent returns -1 - so it fails.
I can't find the programm.
popen()
. – FatalErrorerrno
to see why dup2 failed? – evil ottowaitpid
. If the child has to write more data than will fit in the pipe, it will block on a write and never terminate. Just skip thewaitpid
and let the two run concurrently. (Although you shouldn't allow the child to become an orphan, you cannotwait
for it before you process its output) – William Pursell