Why is my C shell not doing anything when processing commands using pipe?

  Kiến thức lập trình

So, basically, I’ve been fixing my code for some hours, but now I’ve found a problem that I just don’t know what I’m doing wrong.
Basically, I’m making a Linux Shell in C, and I’m trying to implement the pipe “|” operator (considering that there may be multiple pipes). I think I got something on the pipe wrong, because from what I can tell, everything else looks to be working fine, but it doesn’t look like the next commands are getting anything from the pipe (I guess that’s the problem from debugging and testing).

void executaPipe(char** arg, int tamanho) {
  //tamanho = how many "arguments" the command that the user sent has
  //arg = what the user sent, but already separated using strtok in main
  int count = 0, fd[2], i, j = 0;
  char **comando = arg;

  char pip[2] = "|";
  for (i = 0; i < tamanho; i++) {
    if(strcmp(arg[i], pip) == 0) {
      count++;
      arg[i] = NULL;
    }
  }
  
  int result_anterior = STDIN_FILENO;

  for (i = 0; i < count; i++) {
    pipe(fd);

    pid_t pid = fork();

    if(pid == 0) {
      if (result_anterior != STDIN_FILENO) {
        dup2(result_anterior, STDIN_FILENO);
        close(result_anterior);
      }
      dup2(fd[1], STDOUT_FILENO);
      close(fd[1]);

      execvp(comando[0], comando);
    }
    else if (pid > 0) {
      close(result_anterior);
      close(fd[1]);
      result_anterior = fd[0];
      for(j = 0; comando[j] != NULL; j++);
      j++;
      comando = &comando[j];
    }
  }
  if (result_anterior != STDIN_FILENO) {
    dup2(result_anterior, STDIN_FILENO);
    close(result_anterior);
  }
  execvp(comando[0], comando);
}

That’s the function I’ve made (heavily based on another StackOverflow post, but with some modifications) for the pipe processing. I do know for a fact that the rest of the code works just fine, the problem is somewhere here, probably somewhere on the pipe (it may be something very basic, it’s my first time using pipes, so sorry in advance).

if I try doing the command ls -la | grep “main” it just returns nothing, absolutely nothing. Actually, anything that I sendo with grep returns with nothing. But using GDB to debug, it looks like the execvp’s are working fine and calling the commands just fine.

I tried re-checking the code quite some times and tried using close() on different places to see if anything would change, but nothing is really happening.

New contributor

Caputino is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT