Little harvest for Fork

xiaoxiao2021-03-06  38

For the following procedures:

#include #include #include static int flag; int main (void) {INT I; FLAG = 5; for (i = 0; i <5; i ) {if (fork () == 0) {Flag -; Printf ("Flag =% D / N", FLAG); exit (0);}} exit (0);} Compile, the results are as follows: #. / a.out # flag = 4 flag = 4 flag = 4 flag = 4 FLAG = 4 Starting the value of the FLAG that is always considered to be 4, 3, 2, 1, 0. In fact, after the Fork call is successful, share some data space according to the rule parent child process, which is marked as "write time copy" by the kernel. When your child is trying to modify the FLAG value, the kernel immediately copies the page to the new memory space. Therefore, two "flags" are different, modifying the FLAG value in the child process cannot affect the main. That is to say, the WORK process modified variable will be a new child process replicated from the parent process, which does not affect the value of the variable in the parent process. That if you want to change the value of the parent process with implementation sub-processes, use the process between processes such as pipelines, shared memory or use multithreading techniques. Although read books have seen this problem, they accidentally made confused in the actual operation.

转载请注明原文地址:https://www.9cbs.com/read-70627.html

New Post(0)