Frage

I am building a simple shell in c using fork and execlp. I will be given a set of commands separated by pipes. eg: ls -l | wc -l . I am trying to implement a simple shell program in c using. For some strange reason, I am getting a broken pipe error.

void excueteCommand(commandNode* head, int input) {

    int pfds[2] = { -1, -1 };

    if (head->next != NULL) {

        pipe(pfds);
    }

    if (fork() == 0) { /* child */

        if (input != -1) {

            dup2(input, 0);
            close(input);
        }

        if (pfds[1] != -1) {

            dup2(pfds[1], 1);
            close(pfds[1]);
        }

        if (pfds[0] != -1) {

            close(pfds[0]);
        }

        execlp(head->command, head->args, NULL);
        exit(1);
    }

    else { /* parent */

        if (input != -1) {
            close(input);
        }

        if (pfds[1] != -1) {
            close(pfds[1]);
        }

        if (head->next != NULL) {

            thePipenizer(head->next, pfds[0]);
        }
    }
}

Keine korrekte Lösung

Andere Tipps

Hi i don't know what index is. I made a simple prog that work to show you some mistake that you make.

int main()
{
  int   pfds[2] = { -1, -1 };
  int   input;
  char  *argvv = "";
  char  *tab = malloc(500);
  int   i;
  int   nbRead;
  int   stat;

  input = dup(0);
  if (pipe(pfds) == -1)
     exit(-1);
  if (fork() == 0)
    { /* child */
      dup2(pfds[1], 1);
      close(pfds[0]);
      execlp("ls", argvv, NULL);
      exit(-1);
    }
  else
    { /* parent */
      close(pfds[1]);
      wait(&stat);
      do
        {
          nbRead = read(pfds[0], tab, 500);
          for (i = 0; i < nbRead; i++)
            printf("%c", tab[i]);
        } while (nbRead > 0);
      close(pfds[0]);
    }
  return (0);
}

First : Instead of regarding pfds[0] and pfds[1] value, look at the return value of the function pipe. Function pipe return -1 in case of error (see man pipe).

Second : Don't forget to close all open fd, it's important for the system.

If you can told us more about

input

maybe we can found your problem.

In the parent, try resetting pfds. That is:

if( pfds[1] != -1 ) {
    close( pfds[1] );
    pfds[1] = -1;   /* Add this line */
}

By leaving it set to its previous value, it is very likely that subsequent children are closing file descriptors that you do not expect them to be closing.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top