I am trying to create a shell like program . Wrote a sample snippet program to see the execution of ls | wc.
In the sample program the main process creates a childprocess for the execution of each command(using execvp) and passes the output using pipes.
But when I execute the program the waitpid for the second fork() (pid2) is getting block. The program is not proceeding when the waitpid is present.
I get the output if I comment the second waitpid (the child process is running in the background and is printing the output after the main program exits)
What is the issue in the usage of waitpid? Why is it the first waitpid working but not the second waitpid?
Note:1) parse is a library which takes in the input typed and returns each command as a linked list with args and necesary data. Parse is working fine
int main(int argc, char *argv[], char *envp[])
{
Pipe p;
Cmd c;
pipe(lol1);
pipe(lol2);
pid_t pid,pid2;
int i,status,st;
char *host = "armadillo";
fflush(stdout);
printf("%s%% ", host);
p = parse();
c=p->head;
printf("1 \n");
pid=fork();
if(pid==0)
{
dup2(lol1[1],1);
close(lol1[0]);
execvp(c->args[0],c->args);
}
else
{
waitpid(pid,&status,0);
}
printf("2 \n");
c=c->next;
printf("%s \n",c->args[0]);
pid2=fork();
if(pid2==0)
{
dup2(lol1[0],0);
close(lol1[1]);
execvp(c->args[0],c->args);
}
else
{
printf("just before wait pid \n");
waitpid(pid2,&st,0);
close(lol1[0]);
close(lol1[1]);
}
}