Sunday, March 18, 2018

Understanding Fork

I am here trying to understand Fork.  Here is the sample program, for now ignore the libraries included:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
 pid_t child_pid;
 
 printf ("This is the print before Fork\n");
 child_pid=fork();
 printf ("This is the print after Fork\n");
} 

If I execute the program, the output will be

root@kali:/media/root/persistence# gcc fork.c
root@kali:/media/root/persistence# ./a.out
This is the print before Fork
This is the print after Fork
This is the print after Fork

Observe that "This is the print after Fork" will be executed twice. With the Fork, an additional copy of rest of the program will be created and executed.Just like this

If it forks, it is said that the original(termed as Parent) will spawn a child.  Now how can we differentiate whatever that is being executed is Parent or Child.

Here is the example code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
 pid_t child_pid;
 
 printf ("This is the print before Fork\n");
 child_pid=fork();
 printf ("This is the print after Fork : child_pid=%d\n",(int) child_pid);
}

And the output


root@kali:/media/root/persistence# ./a.out 
This is the print before Fork
This is the print after Fork : child_pid=21831
This is the print after Fork : child_pid=0

After the fork, child_pid of the child process will have the value 0. The child_pid of the parent process will have the process ID of the child process(in this case 21831).

Typical fork program will be like

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
 pid_t child_pid;
 
 printf ("This is the print before Fork\n");
 child_pid=fork();
 
 if (child_pid == 0) {
  //This is Child
  printf("\tpid=%d\n",getpid());
  printf("\tparentpid=%d\n",getppid());
  printf("\tChild ID=%d\n",child_pid);
 } else {
  //This is Parent
  printf("pid=%d\n",getpid());
  printf("parentpid=%d\n",getppid());
  printf("Child ID=%d\n",child_pid);
 }
}

For better understanding, there is ps output as well.

root@kali:/media/root/persistence# ps -o pid,ppid,command
  PID  PPID COMMAND
21303  5654 bash
22016 21303 ps -o pid,ppid,command
root@kali:/media/root/persistence# ./a.out 
This is the print before Fork
pid=22244
parentpid=21303
Child ID=22245
 pid=22245
 parentpid=22244
 Child ID=0

Observe in the following image: Bash is the process that runs our programs, its pid underlined red. a.out is the executable process of our fork program, its pid underlined green. Child process is underlined Blue. Rectangle section is different for Parent and Code.