如何在C中同时运行两个子进程? [英] How to run two child processes simultaneously in C?

查看:626
本文介绍了如何在C中同时运行两个子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我进入并发编程,但由于某种原因,我甚至不能得到基本的工作。我有一个名为fork.c的文件,其中包含一个方法main。

So I'm getting into Concurrent Programming, but for some reason I can't even get the basics to work. I have a file called fork.c, which contains a method main. In this method main I fork twice, into child processes 1 and 2.

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

In child 1, I print the character 'A' 50 times.

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

In child 2, I print the character 'B' 50 times.

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

When I run my code, I get the output AAAAA...AAAABBBBBB....BBBBBB. But never something like ABABABABABABAB.... In fact, sometimes I even get BBBBB....BBBBAAAA....AAAAA.

所以为什么我经历这种行为?也许我要完全错了。

So why am I experiencing this behavior? Perhaps I'm going about it completely wrong.

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


推荐答案

/ em>并发运行,但进程在启动后几乎立即结束。

They are running concurrently, but the processes end almost immediately after being started. In other words, they're too short to actually get any real overlap.

编辑:

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

The time needed to start another process is longer than the time it takes to run them. Therefore the chance of overlap is small. (there are also buffering issues which I'll omit)

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

You need each process to do more work than that. Try printing more than 50. Printing more than 10000 will probably be enough.

这篇关于如何在C中同时运行两个子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆