How does fork() return for child process

前端 未结 6 1405
天命终不由人
天命终不由人 2020-12-23 15:33

I know that fork() returns differently for the child and parent processes, but I\'m unable to find information on how this happens. How does the child process receive the re

6条回答
  •  情书的邮戳
    2020-12-23 16:12

    The fork() system call returns twice (unless it fails).

    • One of the returns is in the child process, and there the return value is 0.

    • The other return is in the parent process, and there the return value is non-zero (either negative if the fork failed, or a non-zero value indicating the PID of the child).

    The main differences between the parent and the child are:

    • They are separate processes
    • The value of PID is different
    • The value of PPID (parent PID) is different

    Other more obscure differences are listed in the POSIX standard.

    In one sense, the How really isn't your problem. The operating system is required to achieve the result. However, the o/s clones the parent process, making a second child process which is an almost exact replica of the parent, setting the attributes that must be different to the correct new values, and usually marking the data pages as CoW (copy on write) or equivalent so that when one process modifies a value, it gets a separate copy of the page so as not to interfere with the other. This is not like the deprecated (by me at least - non-standard for POSIX) vfork() system call which you would be wise to eschew even if it is available on your system. Each process continues after the fork() as if the function returns - so (as I said up top), the fork() system call returns twice, once in each of two processes which are near identical clones of each other.

提交回复
热议问题