如何在C中同时运行两个子进程?

所以我进入并发编程,但由于某种原因我甚至无法使用基础知识。 我有一个名为fork.c的文件,其中包含一个方法main。 在这个方法主要我分叉两次,进入子进程1和2。

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

在孩子2中,我打印字符’B’50次。

当我运行我的代码时,我得到输出AAAAA … AAAABBBBBB …. BBBBBB。 但从来没有像ABABABABABABAB那样….事实上,有时我甚至得到了BBBBB …… BBBBAAAA …… AAAAA。

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

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

它们同时运行,但进程在启动后几乎立即结束。 换句话说,它们太短,实际上没有任何真正的重叠。

编辑:

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

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

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

 #include  #include  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