22 September, 2010

C program to fork a new process

Here is a C program to create suboprocess from the current process using fork() system call in Unix. It also identifies and checks both the parent and child process using the process ids...

#include <unistd.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
#include<dirent.h>

int main ()
{
  int flag,flag2;
  int pid,ppid;
  printf("\nHello Worldn");
  flag = fork();
  printf("\nflag :%d",flag);
 
if(flag > 0)
  {         
    printf("\nI'm the Father" );
    printf("\n%dpid ",getpid());
    printf("\n%dppid ",getppid());
   
  }
  else if(flag == 0)
  {     
    printf("\n\n\nI'm the Sonn");
    pid=getpid();
    ppid=getppid();
    printf("\n%dpid ",pid);
    printf("\n%dppid ",ppid);
   
    flag2=fork();
    if(flag2 > 0)
    {         
        printf("\nI'm the sonn" );
        printf("\n%dpid ",getpid());
        printf("\n%dppid ",getppid());
      }
      else if(flag2 == 0)
      {     
        printf("\n\n\nI'm the grandSonn");
        pid=getpid();
        ppid=getppid();
        printf("\n%dpid ",pid);
        printf("\n%dppid ",ppid);
       }
      else
        printf("failure");
   }
  else
    printf("failure");
  printf("\nGoodbye\n\n");
}

0 comments:

Post a Comment

speak out... itz your time !!!

 

Terminal Diary | techblog Copyright © 2009 Gadget Blog is Designed by jintu jacob Powered by Blogger