Introduction
In the realm of operating systems and concurrent programming, the ability to create new processes is crucial. In C programming on a Unix-based system, this can be accomplished using the fork() function. The fork() function creates a new process by duplicating the existing process.
This article will unravel the complexities of the fork() function, explain how it operates with examples, and address common queries related to it.
The fork() Function: What is it?
The fork() function is a system call in Unix-based systems used for creating a new process, termed a child process. The new process is an exact copy of the calling process, the parent process, except for a few values, including its Process ID (PID), Parent Process ID (PPID), and more. The fork() function doesn't take any arguments, but it returns an integer value, the PID of the child process to the parent, and 0 to the child process.
To use the fork() function, we need to include the unistd.h library:
#include <unistd.h>
//An Example of fork() Function
//Consider the following C program:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample() {
// child process because return value zero
if (fork() == 0)
printf("Hello from Child!\n");
// parent process because return value non-zero.
else
printf("Hello from Parent!\n");
}
int main() {
forkexample();
return 0;
}
Output
In the above program, the forkexample() function contains a fork() system call. If the fork() function call creates a child process successfully, it returns 0 in the child process and the child process ID in the parent process. Depending on the returned value, either the parent's or the child's message gets printed.
Also see, Floyd's Triangle in C