【发布时间】:2012-11-17 20:58:40
【问题描述】:
我使用 fork() 是为了让不同的进程运行并打印一条简单的消息。代码的结果让我很困惑。看看代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <math.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <time.h>
int main(void)
{
fork();
fork();
fork();
fprintf(stderr,"hello world\n");
}
输出是:
mario@ubuntu:~/OS$ ./main
hello world
hello world
hello world
hello world
hello world
hello world
mario@ubuntu:~/OS$ hello world
hello world
mario@ubuntu:~/OS$
请注意,我在终端的第一行执行程序,但输出不是我所期望的。请帮我!提前致谢!如果用 printf("......") 更改 fprintf,也会发生同样的事情
编辑:我不明白为什么打印是这样的。终端线前 6 个,旁边 1 个,后面 1 个...
【问题讨论】:
-
你看过
fork函数是如何工作的吗?试着猜猜为什么你有 8 次 'hello world' 使用 3 个分叉。提示,8=2^3。 -
我知道这个事实!我的问题不是 8 个打印,而是它们被终端命令打乱了。我认为程序之前打印 6 是不合理的,一个在终端行旁边 (mario@ubuntu:~/OS$ hello world ),一个在之后..