0
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
void main()
{
  int i = 1;
  pid_t child_pid;
  printf("The main program process ID is %d", (int) getpid());
  printf("%d", i);
  child_pid = fork();
  if (child_pid != 0) {
    i++;
    printf("%d", i);
    printf("This is the parent process, with ID %d \n", (int) getpid());
    printf("The child process is %d ", (int) child_pid);
  } else {
    printf("%d", i);
    printf("This is the child process, with ID %d \n", (int) getpid());
  }
}

我正在使用 C 语言运行该程序,使用该fork()函数。据我了解,当一个进程调用时fork(),会创建一个称为子进程的重复进程。父进程从调用点继续执行,fork()子进程也从同一个地方执行同一个程序。

因此,当我运行我的程序时,我希望输出类似于以下文本:

The main program process ID is 181411This is the child process, with ID 1815
The main program process ID is 18142This is the parent process,with ID 1814
The child process is 1815

但我实际上看到了这个输出:

The main program process ID is 181411This is the child process, with ID 1815
The main program process ID is 181412This is the parent process,with ID 1814
The child process is 1815

意思是孩子先执行程序!!!当我\n在每个语句的末尾放置时,printf输出是正确的!!!

我已经在 Fedora v12 和 rhel 5 发行版上试过了。\nfork()操作之间有什么逻辑关系吗?我该如何解决这个问题?

4

4 回答 4

4

问题是输出是行缓冲的,在您输出\n或显式调用标准输出之前,它不会真正刷新到您的屏幕fflush上。(也就是说,不能保证哪个进程在输出内容时会更快)。

于 2012-11-11T15:38:04.490 回答
3

stdout通常是行缓冲。所以要打印的文本在接收到'\n'.

哪个进程首先写入由操作系统不确定地处理。

打印输出而不需要通过'\n'using触发它strerr是一种选择,因为它通常是无缓冲的。

于 2012-11-11T15:38:11.230 回答
0

我的经验是,使用 stderr 作为 fprintf(stderr,......) 似乎总是写出无缓冲的输出。在段错误停止执行之前,我能够打印一行的内容。用 stderr 再试一次。

于 2012-11-12T07:15:37.427 回答
0

您可以使用:

setbuf(stdout, NULL)

在标准输出流中设置无缓冲输出。

于 2017-03-25T14:00:05.850 回答