Prerequisite – Introduction of fork, getpid() and getppid()
Problem statement – Write a program to create one parent with three child using fork() function where each process find its Id. For example :
Output :parent 28808 28809 my id is 28807 First child 0 28810 my id is 28808 Second child 28808 0 my id is 28809 third child 0 0
Explanation – Here, we had used fork() function to create four processes one Parent and three child processes.
- An existing process can create a new one by calling the fork( ) function.
- The new process created by fork() is called the child process.
- We are using here getpid() to get the process id
- In fork() the total process created is = 2^number of fork()
Note – At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions.
Code 1 – Using
parent 28808 28809 my id is 28807 First child 0 28810 my id is 28808 Second child 28808 0 my id is 28809 third child 0 0
Code 2 – Using
parent 5219 5220 my id is 5217 my parentid is 5215 First child 0 5221 my id is 5219 my parentid is 1 second child 5219 0 my id is 5220 my parentid is 1 third child 0 0 my id is 5221 my parentid is 1
This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- Creating child process using fork() in Python
- Calculation in parent and child process using fork()
- Factorial calculation using fork() in C for Linux
- fork() and memory shared b/w processes created using it
- fork() to execute processes from bottom to up using wait()
- fork() and Binary Tree
- C program to demonstrate fork() and pipe()
- fork() in C
- C vs BASH Fork bomb
- Difference between fork() and exec()
- sorting in fork()
- searching in fork()
- Fork() - Practice questions
- Fork CPP | Course Structure
- Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
- Creating a C++ template in vim in Linux
- Inter-process Communication using a shared stack
- std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
- Double forking to prevent Zombie process
- Exit status of a child process in Linux