如何在C中同时运行两个子进程?
所以我开始学习并发编程,但由于某种原因我什至无法掌握基础知识。我有一个名为 fork.c 的文件,其中包含一个 main 方法。在此方法中,我将 main 分叉两次,分别进入子进程 1 和 2。
在子进程 1 中,我打印字符“A”50 次。
在子 2 中,我打印了字符“B”50 次。
当我运行代码时,我得到输出 AAAAA...AAAABBBBBB....BBBBBB。但从来没有像 ABABABABABABAB 这样的东西......事实上,有时我什至会得到 BBBBB....BBBBAAAA....AAAAA。
那么为什么我会出现这种行为呢?也许我的想法是完全错误的。
#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;
}
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.
In child 1, I print the character 'A' 50 times.
In child 2, I print the character 'B' 50 times.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们同时运行,但进程在启动后几乎立即结束。换句话说,它们太短而无法真正实现任何重叠。
编辑:
启动另一个进程所需的时间比运行它们所需的时间长。因此重叠的机会很小。 (还有我将忽略的缓冲问题)
您需要每个进程做更多的工作。尝试打印超过 50 个。打印超过 10000 个可能就足够了。
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.
EDIT:
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)
You need each process to do more work than that. Try printing more than 50. Printing more than 10000 will probably be enough.
我认为这更容易理解 fork() 的工作原理:
...这是输出:
I think this is much easier to figure how fork() works:
...and here is the output: