0

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]);
  }

}
4

1 回答 1

0

问题在于我在第一个过程中尝试写入的管道。第一个过程结束后,我没有关闭管道的写入端。

因此,当第二个进程由于管道未关闭而尝试读取管道的读取端时,它将不会收到 EOF,因此仍在等待来自管道的输入。

关闭管道的写端,即添加这一行

close(lol1[1]);
pid2=fork();

解决了这个问题

于 2014-10-13T20:13:58.963 回答