0

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");
}
ATB
  • 119
  • 1
  • 9
  • You shouldn't make any assumptions about what process ID the operating system will assign. The only thing you can guarantee is that `fork` returns either 0, -1 or a valid process ID, as per documentation for that function. Be aware that your child process should break out of the loop. Otherwise children will continue forking and you'll end up with `2^k` processes instead of `k` processes. – paddy Nov 24 '22 at 21:02
  • It looks like you made random changes to the code from the linked answer, e.g. `numPipes = 2 * countPipes(input)`. You also left out the creation of the pipes, etc. Voting to close. – Olaf Dietsche Nov 25 '22 at 08:45
  • Maybe read about [`fork`](https://man7.org/linux/man-pages/man2/fork.2.html) – Olaf Dietsche Nov 25 '22 at 08:48

1 Answers1

1

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.

unwind
  • 391,730
  • 64
  • 469
  • 606