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?