#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());
}
}
I'm running this program using the C language, using the fork() function. As I understand it, when a process calls fork(), a duplicate process, called a child process, is created.
The parent process continues executing from the point that fork() was called, and the child process, too, executes the same program from the same place.
So when I run my program, I expect the output be like the following text:
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
But I actually see this output:
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
It means that the child executes the program first!!!
When I put \n at the end of each printf statement the output is correct!!!
I've tried it on the Fedora v12 and rhel 5 distributions.
Is there any logical relation between the \n and the fork() operation? How I can solve this problem?