Search

Using fork -1 Introduction

The function fork() is used to create a new process in linux.
The process which calls the fork is called as the parent and the process that gets created as a result of the fork call is called as the child.
The child process is by default an exact duplicate of the parent but both parent and the child have different process ids.
Once the fork is called from the parent, if a child is created successfully the fork returns the id of the child process to the parent .
The child which being the exact copy of the parent also has a fork call,but in this case the fork returns 0 to the child .
Let us write a simple code to see these steps in the operation.

In the following program :
We print a statement to mark the beginning of the program.
Then we create a child by calling fork.
We check the return value of fork. In the parent process the value will not be zero and in the case of the child the will be zero.
Using this fact we make the parent and child print their respective pids, showing that the two processes are executing independently.

fork.c



Note: We will cover the details of wait() another post

Save it and compile it



execute it



output:



We can see in the output that:
The return values of fork are different.
3974 which is the pid of the child is printed as the return value of fork by parent.
child prints the return value as 0.
Both child and parent print their respective pids.


No comments:

Post a Comment