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
How to create a process in Linux?
A process is a program loaded into memory and currently executing. In simple terms, a process is a program in execution state that the operating system manages and schedules for CPU time.
Creating Processes with fork() System Call
In Linux, a new process is created using the fork() system call. This system call creates a new process by making an exact copy of the calling process's address space. The original process becomes the parent process, while the newly created process becomes the child process.
When fork() is called, both parent and child processes continue execution from the point after the fork() call. The key difference is the return value:
Child process −
fork()returns 0Parent process −
fork()returns the Process ID (PID) of the childError case −
fork()returns -1 if process creation fails
Process Creation Flow
Key System Calls
fork()− Creates a new process (requires<unistd.h>)getpid()− Returns the current process IDgetppid()− Returns the parent process IDwait()− Makes parent wait for child process completion
Example − Creating a Child Process
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
int main() {
pid_t child_pid;
child_pid = fork(); // Create a new child process
if (child_pid < 0) {
printf("fork failed<br>");
return 1;
} else if (child_pid == 0) {
// Child process code
printf("Child process successfully created!<br>");
printf("Child PID = %d, Parent PID = %d<br>", getpid(), getppid());
} else {
// Parent process code
wait(NULL); // Wait for child to complete
printf("Parent process continuing...<br>");
printf("Parent PID = %d, Child PID = %d<br>", getpid(), child_pid);
}
return 0;
}
Output
Child process successfully created! Child PID = 31497, Parent PID = 31496 Parent process continuing... Parent PID = 31496, Child PID = 31497
Key Points
pid_tis a data type representing process IDsEach process has a unique Process ID (PID)
The
wait()system call prevents the parent from terminating before the childBoth processes execute the same code but can be distinguished by
fork()'s return value
Conclusion
Process creation in Linux uses the fork() system call to duplicate the calling process. The parent and child processes can be differentiated by the return value of fork(), enabling them to execute different code paths while sharing the same program structure.
