Hi!

I'm making a simple shell and are using pipes. I'm forking children in
a loop and sending the data through pipes. Afterwards I'm using
waitpid to wait for the children to finish. But I can't get waitpid to
wait for the last child no matter what I do. What am I doing wrong?

thanks for any help.

Heres my code, right now it's just two children:

#include
#include
#include
#include
#include


int main(int argc, char *argv[]) {
pid_t *pid;
doPipe(2, pid);
}

int doPipe(int nr,pid_t *pid) {
int i = 0;
pid_t tempPid[nr];
pid = tempPid;
int status;
int pipVect[nr];
int pip1[2], pip2[2];
pipe(pip1);

while (i < nr) {

if ((pid[i] = fork()) < 0) {
fprintf(stderr, "error");
exit(1);

} else if (pid[i] == 0) { /* The children. */

int destfd;

if (i == 0) {
int destfd;

if (nr > 1) {
destfd = dupPipe(pip1,pip1[1], STDOUT_FILENO);

if (destfd != -1) {
char *cmd[] = { "ls", (char *)0 };

if(execvp ("ls", cmd) < 0) {
perror("argv[0]");
}
}
}
close(destfd);
exit(status);

} else if (i == (nr - 1)) {
printf("Sista steget\n");
int destfd;

if ((i % 2) == 0) {
destfd = dupPipe(pip2, pip2[0], STDIN_FILENO);

} else {
destfd = dupPipe(pip1, pip1[0], STDIN_FILENO);
}
char *cmd[] = { "grep",".c", (char *)0 };

if (execvp ("grep", cmd) < 0) {
perror("argv[0]");
}

close(destfd);
exit(status);
}

} else {
/* Parent. */
}
i++;
}

printf("Pid: %d\n" ,pid[1]);
pid_t pid2;

while ((pid2=waitpid(pid[1], &status, 0)) > 0) {
printf("Child %d has terminated\n", pid2);
}
}


int dupPipe(int pip[2], int end, int destfd) {

if (dup2(end, destfd) < 0) {
perror("Error 1");
destfd = -1;

} else {
close(pip[0]);
close(pip[1]);
}
return destfd;
}