#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()操作之间有逻辑关系吗?我怎样才能解决这个问题?

最佳答案

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

关于c - Linux中的fork()函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13332629/

10-11 22:30
查看更多