简体   繁体   中英

Troubles with a pipe and a fork

I'm making a program that search files and sends it's results to other commands, like a pipe. ls | sort When I run the program nothing happens.The problem I think is that the child's waits for the parent to stop writting in the SO buffer for starting the reading. This is what it sends to stdout and what the pipe should send to the other command.

    troneras@troneras-VirtualBox:~/Escritorio/busca.2012$ ./busca . -n . -print
    ./permisos.txt
    ./busca2.c
    ./mmap.pdf
    ./busca3.c~
    ./cuadernoso4.2011b.pdf
    ./busca.c~
    ./busca.c
    ./busca2.c~
    ./busca3.c

I don't understand what the problem is.


     if(!strcmp(argv[4],"-pipe"))
 {
int pipefd[2];
int pid,dummi;

if (pipe(pipefd)<0){
   perror("pipe");
   exit(1);
}

pid = fork();

if (pid<0){
   perror("fork");
   exit(1); 
}
if (pid == 0){//Child process    
   close(pipefd[1]);//The child is only reading from the pipe
   if(dup2(pipefd[0],0)!=0){perror("dup2");exit(1);}
   close(pipefd[0]);

       char *argumentos[argc-4];
   int j;
   for (j=5;j<argc;j++){
      argumentos[j-5]=argv[j];   
   }         
   argumentos[j-5]= NULL;    

   execvp(argv[5],argumentos);
   perror("execve: ");

}else{ //parent        
   close(pipefd[0]);
   if(dup2(pipefd[1],1)!=1){perror("dup2");exit(1);}
   close(pipefd[1]);

   while(count--){
      if(strcmp(files[count]->d_name,".") && strcmp(files[count]->d_name,"..")){               
         printf("%s/%s\n",argv[1],files[count]->d_name);                       
      free(files[count]);
   }

       wait(&dummi);
}

 }//end pipe                 
 free(files);

BTW There is no reason to duplicate the argv[] array. Instead of

   char *argumentos[argc-4];
   int j;
   for (j=5;j<argc;j++){
      argumentos[j-5]=argv[j];   
   }         
   argumentos[j-5]= NULL;    

   execvp(argv[5],argumentos);

You could just as well do

   execvp(argv[5],argv+5);

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