子进程从父进程继承了用户号和用户组号,用户信息,目录信息,环境(表),打开的文件描述符,堆栈,(共享)内存等。

    经过fork()以后,父进程和子进程拥有相同内容的代码段、数据段和用户堆栈,就像父进程把自己克隆了一遍。

    事实上,父进程只复制了自己的PCB块。而代码段,数据段和用户堆栈内存空间并没有复制一份,而是与子进程共享。只有当子进程在运行中出现写操作时,才会产生中断,并为子进程分配内存空间。由于父进程的PCB和子进程的一样,所以在PCB中断中所记录的父进程占有的资源,也是与子进程共享使用的。这里的“共享”一词意味着“竞争”
    https://www.nowcoder.com/questionTerminal/f70fdf303e3a476d81c3aa9846a2c4a5
    image.png
    image.png

    1. #include <iostream>
    2. #include <unistd.h>
    3. using namespace std;
    4. int g_num = 100;
    5. int main()
    6. {
    7. pid_t pid = fork();
    8. if (pid < 0) {
    9. perror("fork failed");
    10. } else if (pid == 0) {
    11. cout << "this is child process: " << "parent pid=" << getppid() << endl;
    12. } else {
    13. cout << "this is parent process: fork success, pid=" << pid << endl;
    14. }
    15. cout << "cur pid is " << getpid() << endl;
    16. while (1) {
    17. cout << getpid() << " is running\r\n" << endl;
    18. sleep(1);
    19. }
    20. return 0;
    21. }