Linux-fork to create a child process

1. Why do you want to create a child process

(1), every program needs to run a process

(2), in parallel on multiple processes to achieve macro

2, the internal principle fork

(1), the process of division and growth mode.

  If the operating system requires a new process to run a program, the operating system will use an existing process to generate a new copy process.

(2), fork function call will return once twice, the return value is equal to 0 child process, and return a value greater than zero is the parent process.

(3), the typical method of using the fork: the fork is then determined using the return value if, and returns a value greater than zero is the parent process, the child process is equal to 0.

The child process (. 4), the return value of the fork is equal to 0 in the child, is equal to the current fork created in the parent's ID.

3, about the child

(1), the child process has its own independent PCB

(2), the child process is the same kernel scheduling

Operation 4, a parent and child to files

(1), the child inherits the parent process open files

  a, the parent process to open to open a file to get fd, and then create a child process fork. After each write to write to his son in the process fd

  b, test results: continue to write. The reason is in fact the essence of the file pointer fd correspondence between parent and child is associated with each other (especially after O_APPEND signs like the way)

5, each independently of the parent and child open the same file sharing

(1), the parent process open open 1.txt then write, then write the child process open 1.txt, the conclusion is: were written.

The reason is that after the separation of their respective parent and child open 1.txt, this time the two processes have been independent of the PCB, file table also independent, and therefore twice read and write are totally independent.

(2), the use of O_APPEND flag open, the actual test results show that the parent and child can sign O_APPEND independent open fd file pointer to associate, to achieve were written.

6, summed up:

(1), in the absence of the parent process fork a child process what they are doing has a great influence, but the parent process after a fork, in his own if there do no affect the child process. The reason is because the nature of the internal fork actually copy the parent process of PCB generate a new child process and the child process and the parent process has been fully and independently from the operating system OS is scheduled for execution when the fork return.

(2), the ultimate goal is to separate the child to go run another program.

 

Guess you like

Origin www.cnblogs.com/jiangtongxue/p/11230915.html