子进程从父进程继承了用户号和用户组号,用户信息,目录信息,环境(表),打开的文件描述符,堆栈,(共享)内存等。
经过fork()以后,父进程和子进程拥有相同内容的代码段、数据段和用户堆栈,就像父进程把自己克隆了一遍。
事实上,父进程只复制了自己的PCB块。而代码段,数据段和用户堆栈内存空间并没有复制一份,而是与子进程共享。只有当子进程在运行中出现写操作时,才会产生中断,并为子进程分配内存空间。由于父进程的PCB和子进程的一样,所以在PCB中断中所记录的父进程占有的资源,也是与子进程共享使用的。这里的“共享”一词意味着“竞争”
https://www.nowcoder.com/questionTerminal/f70fdf303e3a476d81c3aa9846a2c4a5

#include <iostream>#include <unistd.h>using namespace std;int g_num = 100;int main(){pid_t pid = fork();if (pid < 0) {perror("fork failed");} else if (pid == 0) {cout << "this is child process: " << "parent pid=" << getppid() << endl;} else {cout << "this is parent process: fork success, pid=" << pid << endl;}cout << "cur pid is " << getpid() << endl;while (1) {cout << getpid() << " is running\r\n" << endl;sleep(1);}return 0;}
