Error value returned in pipe

0

They ask me to do a function that first ls the current directory and store it in a file (tmp) and then read that file, grep -c and return the value in the return. I can not get the correct value back to me correctly in int, yes as char.

int do_nfiles (char *pattern)
    {
      t_string s;
      int fd[2],fd2[2];
      char buf[100];
      int val = 10;

      delay ();
      pipe(fd);
      int pid = fork();

       /*Proceso hijo*/
      if(pid == 0){

          fd[0] = open("tmp", O_WRONLY|O_CREAT, 0666);
          dup2(fd[0],STDOUT_FILENO);
          close(fd[0]);
          execlp("ls","ls", NULL);
      }
      else{
          pipe(fd2);
          pid = fork();

          if(pid == 0){
            fd2[0] = open("tmp", O_RDONLY);
            dup2(fd2[0],STDIN_FILENO);
            dup2(fd2[1],STDOUT_FILENO);
            close(fd2[0]);
            execlp("grep","grep","-c",pattern, NULL);
          }

          read(fd2[0], &val, sizeof(val));
          sprintf (s, "[%d] num %d\n", getpid (), val);

        return (val);
      }

      return 0;
    }

If I modify the function and put this:

read(fd2[0],buf,3);

It returns the correct value in char, not int.

    
asked by Shinzu 09.12.2016 в 18:40
source

1 answer

0

Without running it, I see that you use the output of a command as a data entry. All the shell commands that you use show the data as text strings, not as basic language types. It is logical, since they are commands designed to be used by humans .

You have to convert the fd into a stream with fdopen( ) , and, from there, use the input format functions scanf( ) .

    
answered by 09.12.2016 в 19:06