[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
Linux不同进程拥有独立的虚拟地址空间。即使是父子进程也是如此。
当父进程创建一个子进程时,子进程会复制父进程地址空间中的大部分数据资源,包括代码段、变量和文件描述符等(采用写时复制机制)。
因此会有下面有趣的现象,
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include
<wait.h> int main() { char buffer[64] = {0}; //创建子线程 pid_t pid = fork(); if
(pid == -1) { perror("fork"); return -1; } if (pid == 0) { sleep(5);
printf("The address of buffer in child is: %p.\n", buffer); printf("The
buffer[0] is: %c\n", buffer[0]); } else { printf("The address of buffer in
parent is: %p.\n", buffer); buffer[0] = 'J'; printf("The buffer[0] is: %c\n",
buffer[0]); wait(NULL); } }
父子进程中对buffer数组首地址的打印是相同的,但是在父进程中改变buffer[0]的值,却无法影响到子进程中buffer[0]的值。
这是因为父子进程运行在完全独立的虚拟地址空间中,即使buffer的地址指向相同,但是在MMU和操作系统的共同操纵(虚拟地址映射)下,父进程的buffer和子进程的buffer指向的是不同的物理内存地址。
所以,子进程可以复用父进程的变量资源,而不用担心受到父进程的影响,因为自己拿到的是副本。