Thursday, December 26, 2019

Program to execute fork() and find out the process id by getpid() system call.

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

int main()
{
pid_t pid;
pid=fork();
if(pid == 0)
{
printf("\n I am Child %d/n",getpid());
pid=fork();
if(pid==0)
{
printf("\n I am Child of Child %d/n",getpid());
/*pid=fork();
if(pid==0)
{
printf("\n I am Child of Child of child %d/n",getpid());
}
else
{
//printf("\n I am Child of Child %d/n",getpid());
}*/
}
else
{
printf("\n I am Child %d/n",getpid());
}
}
else
{
printf("\n I am Parent %d/n",getpid());
}
printf("\n Hello");

/*
pid_t pid, pid1;

//fork a child process
pid = fork();

if (pid< 0) //error occurred
{
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) //child process
{
pid1 = getpid();
printf("\n child: pid = %d", pid); //line A
printf("\n Child Returned: pid1 = %d", pid1); //line B
}
else //parent process
{
pid1 = getpid();
printf("\n Parent child: pid = %d", pid); //line C
printf("\n Parent Returned: pid1 = %d", pid1); //line D
wait(NULL);
}
  */
return 0;
}

Program to execute fork() and find out the process id by getpid() system call.

#include<stdio.h> #include<sys/types.h> int main() { pid_t pid; pid=fork(); if(pid == 0) { printf("\n I am ...