All about programming in GNU/LINUX

Illustration of fork system call with the help of getpid system call in GNU/LINUX

//download link for the file http://www.slideshare.net/hackintoshrao/forkc
/* —————————————————————– */
/* HACKINTOSH RAO :CODES FOR GNU/LINUX \M/                                              */
/*   This program runs two processes, a parent and a child.  Both of */
/* them run the same loop printing some messages.  Note that printf()*/
/* YOU CAN SEE TWO DIFFERENT PROCESS ID’S PRINTED INDICATING THAT EXECTION IS PERFORMED BY TWO DIFFERENT PROCESSES */

/* —————————————————————– */
/*system calls used :1)fork
                     2)getpid
*/
#include  <stdio.h>
#include  <sys/types.h>
#include <unistd.h>     //header for getpid system call ,to verify go to /usr/include and issue this command “grep -l getpid * “

#define   MAX_COUNT  200

void  ChildProcess(void);                /* child process prototype  */
void  ParentProcess(void);               /* parent process prototype */

void  main(void)
{
     pid_t  pid;

     pid = fork();        //fork system call takes no parameters
                   //a New process in created a the instructions to follow will be parallely executed
     if (pid == 0)
          ChildProcess();
     else
          ParentProcess();
     /*In a normal programming scenario ,Depending on the value of pid either the child process or the parent process function is supposed to be called
       but in this case both the functions gets called as parallel execution of statements takes place after the fork call*/
}
//THESE FUNCTIONS CLEARLY ILLUSTRATES THE LINES EXECUTED BY THE PARENT AND THE LINES EXCUTED BY THE CHILD
//you Will probably see different order of exection of child and parent functions .
void  ChildProcess(void)
{
     int   i;

     for (i = 1; i <= MAX_COUNT; i++)
          printf(”   This line is from child, value = %d,with Process id %d:\n\n”, i,getpid());
     printf(”   *** END OF CHILD PRECESS ***\n”);
}

void  ParentProcess(void)
{
     int   i;

     for (i = 1; i <= MAX_COUNT; i++)
          printf(“This line is from parent, value = %d,with process id %d:\n\n”, i,getpid());
     printf(“*** END OF PARENT***\ PROCESS\n”);
}
Image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s