9B) C program to create child process and print child and parent process ID. [VTU SS&OS]

vtu ss & os 9b
Code:

Explanation:
Aim of this program is to create a child process. print both parent and child process ids there.
Then come out of it. and again in parent process, print both child and parent process ids.

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

include all header files that are necessary.

int main()
{
int status,ppid,mpid,pid;
pid=fork();

main function. four variables to hold the id of process later in the program.
fork() will try to create a child process, if it succeeds, it will return 0 to child process and child process's id to main process. so basically fork() is returning two values to two different processes.
as we will be in child process if fork() succeeds, we check for pid being 0, and if true, we will do job accordingly.

if(pid<0)
{
printf("error in the fork call\n");
exit(0);
}

if fork() returned negative value, it means child process creation failed. so print error message.

if(pid==0)
{
ppid=getppid(); //return parent process id
mpid=getpid(); //return current process id
printf("I am child process executing\nMy own id is: %d\nMy parent id is %d\n",mpid,ppid);
//printf("My own id is %d\n",mpid);
kill();//terminate child process
exit(0);
}

if pid=0 in child process,
get parent process id using getppid() and store in a variable.
get current process id using getpid() and store in a variable.
print those values and call kill() to kill current process.

pid=wait(pid,&status,0);
mpid=getpid();

now this is inside parent process, because child process got killed above. wait(pid,&status, 0) will wait until child gets finished, then stores child process's id. Now you have child's id. get current process id(that is now parent process id) using getpid() and display in the next lines.

printf("I am parent with Id %d\n my child with Id %d\n",mpid,pid);
}

Done!

He is a simple passionate tech freak who himself is an engineering student at Canara Engineering college. He likes App Development, Web designing, Blogging, Youtubing, Debugging and also is a CodeGeek!

Sharing is sexy!

Related Articles

Share your views about this article!