SoFunction
Updated on 2025-03-09

Detailed explanation and examples of Linux programming process fork

Linux fork() detailed explanation:

Before we start, let’s first understand some basic concepts:

1. The program, there is no running executable file

Process, running programs

2. Process scheduling method:

Rotate by time slice
First come first service
Short-term priority
By priority

3. Process status:

Ready ->>   Run ->> Wait
Run ->> Ready //The time is over
Waiting ->> Ready //The waiting conditions are completed

Check the status of the current system process ps auxf

status: 

D    Uninterruptible sleep (usually IO) 
R    Running or runnable (on run queue) 
S    Interruptible sleep (waiting for an event to complete) 
T    Stopped, either by a job control signal or because it is being traced. 
W    paging (not valid since the 2. kernel) 
X    dead (should never be seen) 
Z    Defunct ("zombie") process, terminated but not reaped by its parent. 
<    high-priority (not nice to other users) 
N    low-priority (nice to other users) 
L    has pages locked into memory (for real-time and custom IO) 
s    is a session leader 
l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do) 
+    is in the foreground process group   

4. Parent process/child process. The process that allows a program to run is called the parent process. The called process is called the child process.

5. getpid //Get the process number of the current process
getppid //Get the parent process number of the current process

6. fork //Create a child process. The created child process is a copy of the parent process. Except for the process number, the parent process number is different.

The child process starts running after fork(), and the fork return value it gets is 0
The return value obtained by the parent process is the process number of the child process
When the return value is -1, creation failed

Let’s take a look at a program:

#include &lt;&gt; 
#include &lt;&gt; 
 
int main(void) 
{ 
  pid_t pid ;  
  //printf("hello world \n"); 
 
  //Subprocesses have been generated since fork  pid = fork();  //A new 4G space has been generated, and the copy space has been copied.  //The created child process is a copy of the parent process. Except for the process number, the parent process number and the child process number are different.  //printf("hello kitty\n"); 
  if(pid == 0)   
  { 
    //Subprocess running area 
    printf("child curpid:%d parentpid:%d \n" , getpid() , getppid()); 
    return 0 ;  
  } 
 
  //The parent process run area  printf("parent curpid:%d parentpid:%d \n" , getpid() , getppid()); 
 
  return 0 ;  
} 

Thank you for reading, I hope it can help you. Thank you for your support for this site!