0

I have the following snippet of C code:

int i;
printf("ncams: %d\n", ncams);
for (i = 0; i < ncams; i++) {
    int *pips_fds = malloc(2 * sizeof(int));
    pid_t pid;
    pipe(pips_fds);
    printf("cproc_count in parent: %d, counter i: %d\n", cproc_count, i);// cproc_count is a variable declared above in code
    if ( (pid = fork())== -1) {
        logerr_r("cannot fork");
    } else if (pid == 0) {
        if ( close(pips_fds[1]) < 0) {
            logerr_r("cannot close pipe");
        }
        printf("cproc_count in child: %d, counter i: %d\n", cproc_count, i);
        int j;
        for (j = 0; j < i; j++) {
            free_cproc_id(cprocs[i]);//I don't need this in child process.
        }
        free(cprocs);// I don't need it also here in child process.
    } else {
        CProcID *cproc = malloc(sizeof(CProcID));
        cproc->id = ++cproc_count;
        cproc->pipes = pips_fds;
        if (close(pips_fds[0]) < 0) {
            logerr_r("cannot close pipe");
        }
        cprocs[i] = cproc;
    }

}

Now, the output from this is:

ncams: 2
cproc_count in parent: 0, counter i: 0
cproc_count in parent: 1, counter i: 1
cproc_count in child: 1, counter i: 1
cproc_count in child: 0, counter i: 0
cproc_count in parent: 0, counter i: 1
cproc_count in child: 0, counter i: 1

As you can see, I have i = 1 for two times in parent. Can anybody tell me what I'm doing wrong?

1
  • 1
    What would you expect? Be aware the your threadcount will go exponentially. I suggest you to add process id output so you can distinguish which one was create by which process. Commented Dec 12, 2013 at 12:50

1 Answer 1

3

The reason you have cproc_count in parent: 0, counter i: 1 being printed twice is because it is printed once by the parent, and then printed again by the child after the child has exited it's else if branch and looped around. You probably want to break out of the outer for within the child else if branch so that the child process doesn't also continue looping and forking new children.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.