Write the program to implement the system calls getpid() and getppid(). 

Program Algorithm: 
Step 1 : Declare the variables pid , parent pid , child id and grand chil id. 
Step 2 : Get the child id value using system call fork(). 
Step 3 : If child id value is less than zero then print as “error at fork() child”. 
Step 4 : If child id !=0 then using getpid() system call get the process id. 
Step 5 : Print “I am parent” and print the process id. 
Step 6 : Get the grand child id value using system call fork(). 
Step 7 : If the grand child id value is less than zero then print as “error at fork() grand child”. 
Step 8 : If the grand child id !=0 then using getpid system call get the process id. 
Step 9 : Assign the value of pid to my pid. 
Step 10 : Print “I am child” and print the value of my pid. 
Step 11 : Get my parent pid value using system call getppid(). 
Step 12 : Print “My parent's process id” and its value. 
Step 13 : Else print “I am the grand child”. 
Step 14 : Get the grand child's process id using getpid() and print it as “my process id”.
Step 15 : Get the grand child's parent process id using getppid() and print it as “my parent‟s process id 

System Calls Used: 
1.getpid( ) Each process is identified by its id value. This function is used to get the id value of a particular process. 
2.getppid( ) Used to get particular process parent's id value. 
3.perror( ) Indicate the process error. 


Program Code: 
#include<stdio.h> 
#include<unistd.h> 
#include<stdlib.h> 
int main( ) 
int pid; 
pid=fork( ); 
if(pid== -1) 
{
perror(“fork failed”); 
exit(0); 
if(pid==0) 
printf(“\nChild process is under execution”); 
printf(“\nProcess id of the child process is %d”, getpid()); 
printf(“\nProcess id of the parent process is %d”, getppid()); 
else 
printf(“\nParent process is under execution”); 
printf(“\nProcess id of the parent process is %d”, getpid()); 
printf(“\nProcess id of the child process in parent is %d”, pid()); 
printf(“\nProcess id of the parent of parent is %d”, getppid()); 
return(0); 


Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

1 comments:

  1. this is rather circular since getpid and getppid are already implemented... this wouldn't be how to implement getpid on its own.

    ReplyDelete