Reputation: 97
I am trying to execute a linux command by using execvp in c and it does not show anything. I dont quite understand the dup2() function call. Can any one tell me what i am doing wrong here?
Command To be executed: ls | sort
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdbool.h>
int main()
{
char *cmd[2], *cmd2[3];
cmd[0] = "ls";
cmd[1] = NULL;
cmd2[0] = "sort";
cmd2[1] = NULL;
pid_t id;
id = fork();
int pipe1[2];
int pipe2[2];
pipe(pipe1);
pipe(pipe2);
if(id==0)
{
printf("child process with pid =%d \r\n", getpid());
//the read end of pipe not needed,
close(pipe1[0]);
// we want the stdout (1) of this process to be connected to 1 of pipe1.
dup2(pipe1[1],1); //or dups(pipe1[1], stdout_fileno)
//close it aswell not needed
//close(pipe1[1]);
execvp("ls",cmd);
return 1;
}
pid_t id2 = fork();
if(id2==0)
{
close(pipe1[1]);
dup2(pipe1[0], 0);
close(pipe1[0]);
execvp("sort",cmd2);
//return 1;
}
close(pipe1[0]);
close(pipe1[1]);
waitpid(id,NULL,0);
waitpid(id2, NULL, 0);
//execvp("sort",cmd2);
//printf("parent process with pid =%d \r\n", getpid());
return 0;
}
Upvotes: 0
Views: 40
Reputation: 180171
You need only one pipe, and in fact you use only one, even though you create two. Except you actually create four, because you create the pipes after the first fork(), thus the parent and first child process create two each.
And that appears to be the problem. If you want the two child processes to communicate over a pipe, then they must use the same pipe. They would do so by inheriting the open file descriptors for the pipe ends from the parent process, which requires that they use a pipe created by a process from which both descend (i.e. the parent process), and which was created before either child was forked. As it stands, only the second child is doing that; the first is using a pipe that it creates itself, and which therefore is not connected to anything else.
Upvotes: 1