由linux下的多进程编程引发的关于进程间隔离的思考

源代码放到了三个文件中:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
includeall.h
#include "includeall.h"
int my_sum(int a,int b)//calculate the sum from a to b
{
    int sum=0;
    int i;
    for(i=a;i<=b;++i)
    {
        sum+=i;
    }
    return sum;
}
function.c
 1 #include "includeall.h"
 2 int my_sum(int,int);
 3 int a,b,c;
 4 int main()//calculate the sum from 1 to 100
 5 {
 6     int pid1,pid2;
 7     int * pointa=&a;
 8     int * pointb=&b;
 9     pid1=fork();
10     if(pid1==0)
11     {
12         *pointa=my_sum(1,50);
13         printf("pointa: %p\n",pointa);
14         printf("*pointa: %d\n",*pointa);
15         printf("pointb: %p\n",pointb);
16         printf("*pointb: %d\n",*pointb);
17         //return (a);
18     }
19     else{
20         pid2=fork();
21         if(pid2==0)
22         {
23             *pointb=my_sum(51,100);
24             printf("pointa: %p\n",pointa);
25             printf("*pointa: %d\n",*pointa);
26             printf("pointb: %p\n",pointb);
27             printf("*pointb: %d\n",*pointb);
28             //return (b);
29         }
30         else{
31             wait(0);
32             wait(0);
33             c=(*pointa)+(*pointb);
34             printf("finished\n");
35             printf("sum (from 1 to 100): %d\n",c);
36         }
37     }
38     return 0;
39 }
main.c

程序一运行的时候一共有三个进程,两个子进程分别负责计算1~50的和 和51~100 的和,父进程负责统计这两个子进程的计算结果。

由于对进程间的通信不熟练,于是想到了使用指针的方式。实际运行的时候两个指针变量在三个进程间的值确实是一样的(正如期望的那样),但是在一个进程中通过间接访问的方式对指针指向的内存单元的值进行修改后,在其它进程中使用间接访问的方式取得的值却并不是修改后的(它们的执行顺序没错,是先修改后读取的)。怪哉!

 

猜测可能是操作系统对进程进行隔离造成的,即我们打印出来的内存的地址相同,但不意味着实际对应的内存单元就相同。

内功不足,只是猜测

posted @ 2015-09-19 16:44  张不正  阅读(1316)  评论(0编辑  收藏  举报
返回顶部