New lines at start.
Code:
#include<stdio.h>
#include<sys/types.h>
void main()
{
pid_t pid,pid1;
pid=fork();
if(pid == 0)
{
printf("\nThis is the child of main process with pid=%d and parent id= %d",getpid(),getppid());
pid=fork();
if(pid == 0)
{
printf("\nThis is child of child process with pid = %d and ppid= %d",getpid(),getppid());
}
}
printf("\nProcess with pid %d is terminating.",getpid());
}
Process with pid 2185 is terminating.
This is the child of main process with pid=2186 and parent id= 2185
Process with pid 2186 is terminating.This is the child of main process with pid=2186 and parent id= 2185
This is child of child process with pid = 2187 and ppid= 1
Process with pid 2187 is terminating.
The child prints the blue text, but it is NOT flushed at the point the fork() is called.
This means both it, AND it's child have it in the output buffer (and also in the forked output buffer).
Done properly, the underlined text should never have been forked in the first place.
The output buffer gets flushed when the process exits (both of them), but by then you see the same output twice.
Most sensible and sane people put the \n at the end (\n at the beginning seems to be some TurboC thing, along with the void main horror).
Eg.
Code:
#include<stdio.h>
#include<sys/types.h>
int main()
{
pid_t pid,pid1;
pid=fork();
if(pid == 0)
{
printf("This is the child of main process with pid=%d and parent id= %d\n",getpid(),getppid());
pid=fork();
if(pid == 0)
{
printf("This is child of child process with pid = %d and ppid= %d\n",getpid(),getppid());
}
}
printf("Process with pid %d is terminating.\n",getpid());
return 0;
}
Process with pid 2401 is terminating.
This is the child of main process with pid=2402 and parent id= 2401
Process with pid 2402 is terminating.
This is child of child process with pid = 2403 and ppid= 1
Process with pid 2403 is terminating.
which is altogether far easier to explain.