More you share, more you have!!!

More you share, more you have!!!

C program to create a child process by fork() and print getpid() & getppid()


Q. Write a C program to do the following: Using fork( ) create a child process. The child process prints its own process-id and id of its parent and then exits. The parent process waits for its child to finish (by executing the wait()) and prints its own process-id and the id of its child process and then exits.

Source Code->  

#include<sys/types.h>

#include<stdio.h>

int main()

{

int pid;

pid=fork();

if(pid<0)

printf("fork error");

if(pid==0)

{

printf("\nThis is child process");

printf("\nChild PID: %d", getpid());

printf("\nParent PID: %d", getppid());

execlp("/bin/ls",NULL);

exit(0);

}

else

{

wait(NULL);

printf("\nThis is parent process");

printf("\nParent PID: %d", getpid());

printf("\nChild PID: %d", pid);

exit(0);

}

}


OUTPUT:->

$ gcc 4b.c

$./a.out


This is child process

Child PID: 3122

Parent PID: 3121


This is parent process

Parent PID: 3121

Child PID: 3122


Share on Google Plus
    Blogger Comment
    Facebook Comment

2 comments: