Concurrency 如何在C中分叉n个子对象并让它们执行不同的任务?

Concurrency 如何在C中分叉n个子对象并让它们执行不同的任务?,concurrency,fork,Concurrency,Fork,我试图从父进程创建4个子进程,并让每个子进程执行不同的操作 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++)

我试图从父进程创建4个子进程,并让每个子进程执行不同的操作

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);
}
int main(无效){
int进程=4;
int i;

对于(i=1;i这是一种视错觉。PID的顺序是递增的;)让我解释一下:

  • 首先,创建过程5844
  • 然后创建过程5845
  • 然后创建过程5846
  • 然后创建过程5847
  • 然后,OS调度器选择进程5847并打印“5847”
  • 然后,OS调度器选择进程5846并打印“5846”
  • 然后,OS调度器选择进程5845并打印“5845”
  • 然后,OS调度器选择进程5844并打印“5844”
您无法控制调度程序首先选择哪个进程。但是,如果您在
for
循环的末尾添加
sleep(1);
,我相信PID的顺序会越来越高(除非您达到上限,并且它们会缠绕在一起)

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



你在使用什么操作系统?家长说:“在任何情况下,行的顺序都应该是递增的。

PID可以是任意顺序的-你为什么不这么认为?谢谢你对发生的事情的很好的解释。这让事情变得更清楚了。我正在使用Ubuntu并添加睡眠(1)允许它以递增的顺序打印。您能解释一下使用wait的最终for循环吗?它似乎运行sum,而不管它是否在那里。@omgitsbd-with the wait(),父进程等待子进程完成。如果忽略它,父进程可能会比子进程更早退出:这将杀死剩余的子进程,您只会看到子进程的部分输出,或者根本看不到输出。但是,如果子进程比父进程快,您将无法观察到差异。Exc请注意,您必须注意不要产生太多僵尸=>但在本例中,这不是问题,因为当父级退出时,僵尸会被垃圾收集。
#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);
    }
}
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