/*
This program explain about the basic process creation in the linux operating system
1) its obvious that statement after the fork are executed twice. once on the behalf of main program and second as child process
*/
#include
int main()
{
int pid;
printf("\nThis will be executed only once [%d] [%d]\n", getpid(), getppid());
fork();
printf("\nTHis will be executed twice\n", getpid(), getppid());
return 0;
}
Output :
This will be executed only once [4665] [4299]
THis will be executed twice [4666] [4665]
THis will be executed twice [4665] [4299]
/*
program will show some clever use of pid. In this way you can segregate the parent process and child process code
one more important point fork returns zero to the child process.
why it return zero is, the answer is its the kernel implemenation of the kernel code
http://fxr.watson.org/fxr/source/kern/kern_fork.c?v=FREEBSD8
he code is a bit confusing if you're not used to reading kernel code, but the inline comments give a pretty good hint as to what's going on.
The most interesting part of the source with an explicit answer to your question is at the very end of the fork() definition itself -
if (error == 0) {
td->td_retval[0] = p2->p_pid;
td->td_retval[1] = 0;
}
"td" apparently holds a list of the return values for different threads. I'm not sure exactly how this mechanism works (why there are not two separate "thread" structures). If error (returned from fork1, the "real" forking function) is 0 (no error), then take the "first" (parent) thread and set its return value to p2 (the new process)'s PID. If it's the "second" thread (in p2), then set the return value to 0.
There is one more thing you can notice, only pid is set to zero not all the local variable, which tells justifies the kernel things
*/
#include
int main()
{
int pid;
int temp;
pid = fork();
if(0 == pid)
{
printf("\n I am child process [%d] [%d]\n", getpid(), getppid());
printf("Temp and Pid [%d] [%d]", temp, pid) ;
}
else
{
printf("\n I am Parent process [%d] [%d]\n", getpid(), getppid());
printf(" Temp and Pid [%d] [%d]", temp, pid) ;
}
return 0;
}
Output:
I am child process [4885] [4884]
Temp and Pid [-1080938856] [0]
I am Parent process [4884] [3314]
Temp and Pid [-1080938856] [4885]