Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
fork() in C
In this section we will see what is the fork system call in C. This fork system call is used to create a new process. This newly created process is known as child process. The current process which is creating another child process is called the parent process.
A child process uses the same program counter, CPU register, same files that are used by the parent process.
Syntax
#include <sys/types.h> #include <unistd.h> pid_t fork(void);
Return Value
The fork() does not take any parameter, it returns integer values. It may return three types of integer values −
- Negative Number: It returns negative number when child process creation is failed
- Zero Value: It returns Zero for the newly created child process
- Positive Value: The positive value is returned to the parent process.
Example: Basic Fork Usage
Here is a simple example to demonstrate how fork() creates a child process −
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
fork(); // make a child process of same type
printf("Fork testing code
");
return 0;
}
The output of the above code is −
Fork testing code Fork testing code
Example: Identifying Parent and Child Process
To differentiate between parent and child processes, we can check the return value of fork() −
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t process_id = fork();
if (process_id == 0) {
printf("This is child process. PID: %d
", getpid());
} else if (process_id > 0) {
printf("This is parent process. PID: %d, Child PID: %d
",
getpid(), process_id);
} else {
printf("Fork failed
");
}
return 0;
}
The output of the above code is −
This is parent process. PID: 1234, Child PID: 1235 This is child process. PID: 1235
Note: The fork() system call is Unix/Linux specific and may not work on Windows systems. Use a Unix/Linux environment or compiler that supports POSIX functions.
Key Points
- Both parent and child processes execute the code after fork() independently
- The child process gets a copy of the parent's memory space
- Process IDs (PID) are unique for each process
Conclusion
The fork() system call is essential for creating new processes in Unix/Linux systems. Understanding its return values helps distinguish between parent and child processes for proper program flow control.
