Python:How os.fork() works?

前端 未结 3 1868
野趣味
野趣味 2020-12-04 16:46

I am learning multiprocessing in python. I tried multiprocessing and after I read the source code of multiprocessing module, I found it use os.fork(), so I wrot

3条回答
  •  独厮守ぢ
    2020-12-04 17:14

    As both answers cover almost everything about how os.fork() works. I wanted to add some more specific information regarding the case.

    Fork system call is used for creating a new process which is called the child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process created both processes will execute (Execution state; heap, stack, and processor registers) the next instructions following fork() system call(system call that creates a new process identical to the calling one, makes a copy of the text, data, stack, and heap). fork() does not take parameters and returns an integer value. After successfully call to fork(), the child process is basically an exact duplicate of the parent process. fork is Unix system call which is used to create a new process. System call way to request services from the kernel. fork returns a value, if the value greater than 0, that means successful fork but you may get below 0 as well, this might be that process out of memory or other errors, it cannot be created and it will raise an error. If it is equal to zero it is a child greater than 0, which means parent process. So the process runs concurrently, we archive here parallelization, but everything after fork call will be executed.

    Calling fork duplicates process that is referred to parent. fork means two different identical copies of address base one for child one for the parent process. Both proses are exact copy of each other except PID and a few others. Since both processes have identical but separate address spaces, those variables initialized before the fork() call have the same values in both address spaces. Since every process has its own address space, any modifications will be independent of the others. In other words, if the parent changes the value of its variable, the modification will only affect the variable in the parent process address space. Other address spaces created by fork() calls will not be affected even though they have identical variable names.

    Upon fork() all resources owned by the parent are duplicated and the copy is given to the child, In Linux, fork() is implemented through the use of Copy-on-Write pages. Copy on Write or simply CoW is a resource management technique. More about CoW

    You can use fork, in case if you want to create parallel program with multiple processes.

提交回复
热议问题