【问题标题】:How to run two child processes simultaneously in C?如何在 C 中同时运行两个子进程?
【发布时间】:2011-09-20 01:45:48
【问题描述】:

所以我开始学习并发编程,但由于某种原因,我什至无法掌握基本知识。我有一个名为 fork.c 的文件,其中包含一个方法 main。在这个方法中,我分叉了两次,进入子进程 1 和 2。

在孩子 1 中,我打印了 50 次字符“A”。

在孩子 2 中,我打印了 50 次字符“B”。

当我运行我的代码时,我得到输出 AAAA...AAAABBBBBB....BBBBBB。但是从来没有像 ABABABABABABAB 这样的东西....事实上,有时我什至会得到 BBBBB....BBBBAAAA....AAAA。

那么为什么我会遇到这种行为?也许我完全错了。

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

void my_char(char n) {
    write(1, &n, 1);
}

int main() {
    int status;
    pid_t child1, child2;

    if (!(child1 = fork())) {
        // first childi
        int a;
        for (a = 0; a < 50; a++) {
            my_char('A'); 
        }
        exit(0);
    } else if (!(child2 = fork())) {
        // second child
        int a;
        for (a = 0; a < 50; a++) {
            my_char('B');
        }
        exit(0);
    } else {
        // parent
        wait(&child1);
        wait(&child2);
        my_char('\n');
    }

    return 0;
}   

【问题讨论】:

  • fork 可能不是大多数人在说“并发编程”时所想到的......
  • 为什么?抱歉,对此很陌生。
  • fork 创建一个新的单线程进程。 “并发”通常是指单个进程内的多线程。
  • 您的进程除了争夺一种资源,即输出设备,什么都不做。那么它们如何同时运行呢?

标签: c concurrency parallel-processing


【解决方案1】:

它们正在同时运行,但进程几乎在启动后立即结束。换句话说,它们太短而无法真正重叠。

编辑:

启动另一个进程所需的时间比运行它们所需的时间长。因此重叠的可能性很小。 (还有缓冲问题我会省略)

您需要每个流程做更多的工作。尝试打印超过 50 个。打印超过 10000 个可能就足够了。

【讨论】:

  • 完美。 proof。非常感谢。我开始担心我不知道 fork 是如何工作的。
  • 或者你可以在循环内调用 sleep 一点。根据您的操作系统/编译器尝试usleepSleep
【解决方案2】:

我认为这更容易理解 fork() 的工作原理:

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

int main() {
    pid_t child1, child2;
    printf("Start\n");
    if (!(child1 = fork())) {
        // first childi
        printf("\tChild 1\n");
        sleep(5);
        exit(0);
    } else if (!(child2 = fork())) {
        // second child
        printf("\tChild 2\n");
        sleep(5);
        exit(0);
    } else {
        // parent
        printf("Parent\n");
        wait(&child1);
            printf("got exit status from child 1\n");
        wait(&child2);
            printf("got exit status from child 2\n");
    }

    return 0;
}

...这是输出:

    Start
        Child 1
    Parent
        Child 2
    got exit status from child 1
    got exit status from child 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多