进程的地址空间是相互独立的,也就是说,每个进程都有自己的页目录和页表。那么一旦调用fork(),父子进程的地址空间就是两个空间,如果子进程对某部分内存进行了修改,父进程是看不到的。比如下面这个测试:
- #include <stdio.h>
- #include <sys/types.h>
- #include <unistd.h>
- struct xx
- {
- int a;
- };
- int main()
- {
- pid_t pid;
- struct xx s;
- s.a = 5;
- struct xx* sp = &s;
- pid = fork();
- if (pid > 0)
- {
- printf("parent show %p, %p, a = %d\n", sp, &sp->a, sp->a);
- sp->a = 4;
- //while(sp->a > 0);
- sleep(10);
- printf("parent show %p, %p, a = %d\n", sp, &sp->a, sp->a);
- printf("parent exit\n");//exit(0);
- }
- else
- {
- //while(sp->a == 5);
- printf("child show %p, %p, a = %d\n", sp, &sp->a, sp->a);
- sp->a = -1;
- printf("child change a to %d\n", sp->a);
- }
- return 0;
- }
编译运行结果是:
- [root@141 test]# gcc test.c
- [root@141 test]# ./a.out
- parent show 0x7fffe86b64a0, 0x7fffe86b64a0, a = 5
- child show 0x7fffe86b64a0, 0x7fffe86b64a0, a = 5
- child change a to -1
- parent show 0x7fffe86b64a0, 0x7fffe86b64a0, a = 4
- parent exit
一切都明了~
调了一晚上的项目,原来是父子进程的处理出了问题。基础知识还是很重要!
转载于:https://blog.51cto.com/luckybins/633547