Return Values of Fork ()
Understanding the return values of fork() is crucial when we are using a function in our code:
- Return Value of -1: If fork() returns -1, it signifies that the creation of a child process was unsuccessful. This typically occurs when system resources are exhausted, and no more processes can be created.
- Return value of 0: When fork() returns 0, it means you are in the newly created child process. This is a key differentiator that allows the program to execute different logic or tasks in the parent and child processes.
- Positive return value (Process ID): If fork() returns a positive value, it is indicative of the parent process. This value contains the Process ID (PID) of the newly created child process. The PID is essential for tracking and managing multiple processes concurrently.
Example of Fork() in C
C
#include <stdio.h> #include <unistd.h> int main() { pid_t child_pid; //create a child process child_pid = fork(); if (child_pid < 0) { // Error occurred while forking printf ( "Fork failed\n" ); return 1; } else if (child_pid == 0) { // Child process printf ( "Child process: PID = %d\n" , getpid()); printf ( "Hello from the child!\n" ); } else { // Parent process printf ( "Parent process: PID = %d\n" , getpid()); printf ( "Child process created with PID = %d\n" , child_pid); } return 0; } |
Output
Parent process: PID = 1915 Child process created with PID = 1919
Fork Function Call
In this article, we are going to see the fork function call in detail with the help of an example. A function call is an operating system call that is used to create a copy of a process which is also called a child process. This function call is used in a system that supports multitasking.
Contact Us