0

我希望设计一个从中调用的函数main,它将分叉任何进程进入睡眠状态,然后更新包含所有分叉 pid 和它们的计数器的“进程数组”。它似乎有效,只有其他进程也被分叉(这里是 pid-111957),我不确定从哪里来。测试运行给出:

Parent 11954 forks off children..
Children started: 2
Proc 11955 started
Proc 11956 started
Children started: 1
Child -1 terminated with status 0
Children started: 1
Proc 11957 started
Children started: 0
Child 11957 terminated with status 0
Child 11955 terminated with status 0
Child 11956 terminated with status 0

编码:

#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

#define MAXPROC 100

void fork_off(int * proc_t, int * proc_i) {
    int f = fork();
    if (f == 0) {
        fprintf(stderr, "Proc %d started\n", getpid());
        usleep(5000000);
    } else {
        proc_t[*proc_i] = f;
        (*proc_i)++;
    }
}

int main(void) {

    int proc_table[MAXPROC], proc_index, status, i;
    proc_index = status = i = 0;

    printf("Parent %d forks off children..\n", getpid());

    fork_off(proc_table, &proc_index);
    fork_off(proc_table, &proc_index);

    printf("Children started: %d\n", proc_index);

    for (i = 0; i < proc_index; i++) {
        printf("Child %d terminated with status %d\n", 
                waitpid(proc_table[i], &status, 0), status);
    }

    return 0;
}

我只想分叉两个进程,而不是更多。是什么导致了这种行为?

4

1 回答 1

0

您的代码的问题在于,在子进程休眠后,它们会从父进程返回fork_off并重复父进程正在执行的所有操作。

void fork_off(int * proc_t, int * proc_i) {
    int f = fork();
    if (f == 0) {
        fprintf(stderr, "Proc %d started\n", getpid());
        usleep(5000000);
        exit (0); /* exit() closes the entire child process
                   * instead of simply return from the function
                   */
    } else if (f > 0) { /* Make sure there isn't an error being returned.
                         * Even though I've never seen it happen with fork(2),
                         * it's a good habit to get into
                         */
        proc_t[*proc_i] = f;
        (*proc_i)++;
    } else { /*  Adding to the aforementioned point, consider changing
              *  the return type to int - so that you can return -1
              *  and check for error.
              */
    }
}
于 2013-06-09T21:45:22.690 回答