First, I Saw already the all posts before. I took already a code from here https://stackoverflow.com/a/8439286/14888108
I have a problem I didn't know how to solve: when I do fork the pid is not 0 no matter what. its a random number started like : 4013,4014 if I give [input: echo atb | grep "b"]
Here is my code:
EDITED AFFTER MISTAKE IN THE CODE SAME PROBLEM:
void Pipeline(char *input) {
int numPipes = 2 * countPipes(input);
int k = commends(input);
int j = 0;
for (int i = 0; i < k; i++) {
int pid = fork();
if (pid == 0) {
if (i != k-1) {
if (dup2(pipefds[j + 1], 1) < 0) {
perror("dup2");
exit(EXIT_FAILURE);
}
}
//if not first command&& j!= 2*numPipes
if (j != 2*numPipes && i != 0) {
if (dup2(pipefds[j - 2], 0) < 0) {
perror(" dup2");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < 2 * numPipes; i++) {
close(pipefds[i]);
}
if (execvp(vec[i], vec) < 0) {
perror(vec[i]);
exit(EXIT_FAILURE);
}
} else if (pid < 0) {
prev++;
perror("error");
exit(EXIT_FAILURE);
}
j += 2;
}
for (int i = 0; i < 2 * numPipes; i++) {
close(pipefds[i]);
}
for (int i = 0; i < numPipes + 1; i++) {
wait(NULL);
}
printf("DONE!\n");
}