In Linux, the system call that generates a new process is the fork function. This function name means "Forks" in English. Why is this name used? Because a process is running, if fork is used, another process is generated, so the process is "Forked", so this name is very good. The following describes how to use fork. This program demonstrates the basic framework of using fork:
Void main (){
Int I;
If (Fork () = 0 ){
/* Sub-process program */
For (I = 1; I <1000; I ++)
Printf ("this is child process \ n ");
}
Else {
/* Parent process program */
For (I = 1; I <1000; I ++)
Printf ("this is Process \ n ");
}
}
After the program runs, you can see that the screen displays one thousand pieces of information each printed by the child process and the parent process. If the program is still running, you can use the ps command to see that there are two running programs in the system.
So what happens when this fork function is called? When a program calls the fork function, the system prepares the preceding three segments for a new process. First, the system allows the new process and the old process to use the same code segment, because their programs are the same, the system copies a copy of the data segment and stack segment to the new process. In this way, all data of the parent process can be left to the child process. However, once a child process starts running, it inherits all the data of the parent process, but in fact the data has been separated and there is no impact between them, that is, they no longer share any data. If the two processes want to share any data, they need to use another function (shmget, shmat, shmdt, and so on. Now there are two processes. For the parent process, the fork function returns the process Number of the subroutine, and for the subroutine, the fork function returns zero. In this way, for the program, as long as you determine the return value of the fork function, you will know whether you are in the parent process or child process.
Readers may ask, if a large program is running and its data segments and stacks are large, and a fork will be copied once, isn't the system overhead of fork very high? In fact, Unix has its own solution. As you know, CPU generally allocates space in units of "pages", such as Intel's CPU, the page of which is usually 4 K bytes, both the Data Segment and the stack segment are composed of many "pages". The fork function copies these two segments, but they are logical and not physical. That is to say, when fork is actually executed, the data segments and stack segments of the two processes in the physical space are still shared. When a process writes data, at this time, the data between the two processes is different, and the system physically separates the different "pages. The space overhead of the system can be minimized.