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 processfork() returns 0

  • Parent processfork() returns the Process ID (PID) of the child

  • Error casefork() returns -1 if process creation fails

Process Creation Flow

Process Creation with fork() Parent Process calls fork() Child Process (fork returns 0) Parent Process (fork returns child PID)

Key System Calls

  • fork() − Creates a new process (requires <unistd.h>)

  • getpid() − Returns the current process ID

  • getppid() − Returns the parent process ID

  • wait() − 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_t is a data type representing process IDs

  • Each process has a unique Process ID (PID)

  • The wait() system call prevents the parent from terminating before the child

  • Both 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.

Updated on: 2026-03-17T09:01:38+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements