在循环中分叉会导致奇怪的行为

时间:2013-12-12 12:35:19

标签: c fork

我有以下C代码片段:

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;
    }

}

现在,这个输出是:

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

如您所见,我在父母身上有i = 1两次。谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:3)

cproc_count in parent: 0, counter i: 1被打印两次的原因是因为它由父母打印一次,然后在孩子退出它的else if分支并且环绕之后由孩子再次打印。您可能希望从break分支中的外部forelse if,以便子进程不会继续循环并分叉新的子进程。