Home > Enterprise >  Implementation of multiple pipelines in C
Implementation of multiple pipelines in C

Time:11-25

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:

void Pipeline(char *input) {
    int numPipes = 2 * countPipes(input);
    printf("The number of the Pipes is :%d\n",countPipes(input));
    char delim[] = "|";
    char *token;
    char *vec[1024] = {0};
    int k = 0;
    for (token = strtok(input, delim); token; token = strtok(NULL, delim)) {
        vec[k  ] = token;
    }
    vec[k] = NULL;
    int pipefds[numPipes];
    for (int i = 0; i < k; i  ) {
        printf("The current vec[i] is: %d, %s\n",i,vec[i]);
        if (pipe(pipefds   i * 2) < 0) {
            perror("error pipelines\n");
            exit(EXIT_FAILURE);
        }
    }
    int j = 0;
    int prev;
    for (int i = 0; i < k; i  ) {
        int pid = fork();
        prev = pid;
        if (pid == prev 1) {
            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");
}

CodePudding user response:

Not an answer, but ... you never check for pid == 0.

Furthermore, pid will never equal prev 1, because you ensure that prev = pid right before the check:

int pid = fork();
prev = pid;
if (pid == prev 1) {
    // this code path is never reached
} else if (pid < 0) {
    // handle error
}

CodePudding user response:

These lines:

int pid = fork();
prev = pid;
if (pid == prev 1) {

don't seem to make a lot of sense. If you copy pid into prev first, how can pid then ever be equal to prev 1?

Also, you seem to be expecting a particular sequence of process id:s, that is not very likely or portable (or even nice). Other processes are busy creating and destroying processes in the background, I don't think you can assume that your particular process has a private pid space to fill.

  • Related