2012-11-29 34 views
2

我为了使不同proccesses运行,但打印的代码counfuses我一个简单的message.The结果使用fork()..看看代码: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"); 

} 

,输出为:

[email protected]:~/OS$ ./main 
hello world 
hello world 
hello world 
hello world 
hello world 
hello world 
[email protected]:~/OS$ hello world 
hello world 

[email protected]:~/OS$ 

请注意,我在终端的第一行执行程序,但输出是不是我的预期。请帮帮我!提前致谢!如果fprintf用printf(“......”)改变,也会发生同样的情况

编辑:我不明白为什么打印是这种方式。在终端线旁边有6个,之后有1个...

+0

你看过'fork'函数的工作原理吗?尝试猜猜为什么你使用3把叉子8次'hello world'。提示,8 = 2^3。 –

+0

我知道这个事实!我的问题不是8打印,而是它们被终端命令打乱。我不觉得它合理的程序打印6之前,终端线(马里奥@ Ubuntu的:〜/ OS $你好世界)旁边和一个.. – JmRag

回答

3

当父程序退出时,运行父程序的shell会在屏幕上打印shell提示符[email protected]:~/OS$。在提示后,将打印任何尚未打印的子程序hello world。如果您希望提示不出现在所有hello world之前,则需要让父母等待所有子和孙程序终止。

检查this看看如何让父母等待。

+0

Thx很多!这真的让我摆脱了许多麻烦! – JmRag

0

您正在创建8个进程。每个fork将该过程分成两部分。它的原始父节点完成了我仍在执行的其他进程。因此,如果原始进程完成执行,shell会执行并打印提示,尽管其他进程仍在执行。