#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 发行版上试过了。\n
和fork()
操作之间有什么逻辑关系吗?我该如何解决这个问题?