【问题标题】:fork() and stderr with terminal带有终端的 fork() 和 stderr
【发布时间】: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 ),一个在之后..

标签: c terminal fork stderr


【解决方案1】:

当父程序退出时,运行父程序的shell在屏幕上打印shell提示符mario@ubuntu:~/OS$。到那时尚未打印hello world 的任何子程序都将在提示后打印。如果您希望提示符不出现在所有hello worlds 之前,您需要让父级等待它的所有子程序和孙子程序终止。

查看this 了解如何让父母等待。

【讨论】:

    【解决方案2】:

    您正在创建 8 个进程。每个fork 将进程一分为二。它的原始父级完成了我仍在执行的其他进程。因此,如果原始进程完成执行,则尽管其他进程仍在执行,shell 仍会执行并打印提示。

    【讨论】:

      猜你喜欢
      • 2013-06-15
      • 2018-01-08
      • 2022-12-07
      • 1970-01-01
      • 2011-10-08
      • 2011-04-22
      • 2018-04-03
      • 1970-01-01
      • 2010-09-26
      相关资源
      最近更新 更多