進程的地址空間是相互獨立的,也就是說,每個進程都有自己的頁目錄和頁表。那麼一旦調用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
一切都明了~
調了一晚上的項目,原來是父子進程的處理出了問題。基礎知識還是很重要!
本文出自 “小強技術博客” 博客