A process with ID 0 is typically a scheduling process. is often referred to as the Swap process (swapper), which is a system process in the kernel.
A process with ID 1, called the init process, is a normal user process that is not part of the kernel and is called by the kernel.
An existing process can call the fork function to create a new process (child process). The fork function is called once. Returned two times .
The child process return value is 0. The parent process return value is the process ID of the child process.
When a child process is forked, the child process has a separate copy of the data segment, heap, and stack, but the parent and child processes share the body segment (see the article "C program's storage space layout" for program distribution). But today very many implementations do not completely replicate data segments, heaps, stacks, and start when the parent and child processes share all segments, only when a process attempts to change a zone to replicate that area.
This is called copy-on-write (COW).
Test code:
#include <stdio.h> #include <unistd.h> int glob = 123; int main (void) { int x = 456; pid_t pid; if (PID = fork ()) < 0) return-1; else if (PID = = 0) { //Sub-process glob++; x + +; } else sleep (2); The parent process sleeps for two seconds printf ("pid =%d, Glob =%d, x =%d\n", Getpid (), glob, x); return 0;}
Execution Result:
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbmvzdgxlcg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">
From the implementation results can be seen. Data segments and stacks are independent of each other. Since Glob is stored in the initialization data segment, x is stored in the stack, and the child process changes it without affecting the parent process.
Two common ways to use fork:
Reference: Advanced programming for the UNIX environment p171-p176.
"Linux Programming" process identifiers and fork functions