简体   繁体   中英

Piping in a basic shell implementation

In an assignment we were asked to implement piping. I was able to do so, but the problem which I am encountering is that when I enter the command

ls | grep 'a.out'

then the output is

a.out

a.out

but when I do

ls | wc

The output comes only once. Can anyone point out the mistake in the code ?. The code is as follows :

void execute_pipe(char **argv,char **args)
{

int pfds[2];
pid_t pid,pid2;
int status,status2;
pipe(pfds);
if ((pid = fork()) < 0) {    
      printf("*** ERROR: forking child process failed\n");
      exit(1);
 }
if ((pid2 = fork()) < 0) {    
      printf("*** ERROR: forking child process failed\n");
      exit(1);
 }
if (pid==0) {
    close(1);     
    dup(pfds[1]);  
    close(pfds[0]); 
close(pfds[1]);
    if(execvp(argv[0],argv)<0){
        printf("**error in exec");
    }
} 
else if(pid2==0){

    close(0);       
    dup(pfds[0]);  
    close(pfds[1]);
close(pfds[0]);
    if(execvp(args[0],args)<0){
    printf("**error in exec");

}
}
else{
    close(pfds[0]);
    close(pfds[1]);
    while (wait(&status) != pid)  ;
    while (wait(&status2) != pid2)  ;
        }
}

I ma quite sure that there are no stray prints and there is only one a.out in the directory.

You run the second fork in both the parent and first child processes. You should only do the second fork if pid is non-zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM