如何分叉 n children 并让它们在 C 中执行不同的任务?

How to fork n children and have them execute different tasks in C?

我正在尝试从 parent 创建 4 个 children 进程,并让每个 child 执行不同的操作。

int main(void) {
int processes = 4;
int i;
for (i = 1; i <= processes; i++) {
    if (fork() == 0) {
        printf("pid: %d\n", getpid());
        exit(0);
    }
}
int status;
for (i = 1; i <= processes; i++)
    wait(&status);
}

现在输出生成 进程号:5847 进程号:5846 进程号:5845 pid: 5844

为什么 pid 的顺序是递减而不是递增?我没有正确使用 fork() 来创建 children 吗?

这是一种视错觉。 PID 的顺序是递增的 ;) 让我解释一下:

  • 首先创建进程5844
  • 然后创建进程5845
  • 然后创建进程5846
  • 然后创建进程5847
  • 然后 OS 调度程序选择进程 5847 并打印“5847”
  • 然后 OS 调度程序选择进程 5846 并打印“5846”
  • 然后 OS 调度程序选择进程 5845 并打印“5845”
  • 然后 OS 调度程序选择进程 5844 并打印“5844”

您无法控制调度程序首先选择哪个进程。但是,如果您将 sleep(1); 添加到 for 循环的末尾,我确信 PID 将按递增顺序排列(除非您达到上限并且它们环绕。)

至少Linux和OS X按递增顺序生成PID,不知道其他类Unix操作系统。


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    int processes = 4;
    int i;
    int fork_result;
    int number_of_children;
    for (i = 1; i <= processes; i++) {
        fork_result = fork();
        if (fork_result > 0) {
            printf("parent says: hello child #%d, how are you?\n", fork_result);
            number_of_children++;
        } else if (fork_result == 0) {
            printf("pid: %d\n", getpid());
            exit(0);
        } else if (fork_result < 0) {
            printf("parent says: fork() failed\n");
        }
    }
    int status;
    for (i = 1; i <= number_of_children; i++) {
        wait(&status);
    }
}

在我的系统 (OS X 10.10.5) 上打印:

parent says: hello child #2577, how are you?
parent says: hello child #2578, how are you?
pid: 2577
pid: 2578
parent says: hello child #2579, how are you?
parent says: hello child #2580, how are you?
pid: 2579
pid: 2580

你在用什么OS? "parent says:" 行在任何情况下都应按递增顺序排列。