zoukankan      html  css  js  c++  java
  • 由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
    ",pointa);
    14         printf("*pointa: %d
    ",*pointa);
    15         printf("pointb: %p
    ",pointb);
    16         printf("*pointb: %d
    ",*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
    ",pointa);
    25             printf("*pointa: %d
    ",*pointa);
    26             printf("pointb: %p
    ",pointb);
    27             printf("*pointb: %d
    ",*pointb);
    28             //return (b);
    29         }
    30         else{
    31             wait(0);
    32             wait(0);
    33             c=(*pointa)+(*pointb);
    34             printf("finished
    ");
    35             printf("sum (from 1 to 100): %d
    ",c);
    36         }
    37     }
    38     return 0;
    39 }
    main.c

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

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

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

    内功不足,只是猜测

  • 相关阅读:
    阿里云CentOS主机修改默认SSH登录的22端口
    python跨文件设置全局变量
    python类装饰器
    执行python manage.py celery beat-l info 时报错 SystemError:<class 'OSError'>可能还会有其他报错
    利用Python脚本实现发送邮件
    python操作pymysql
    python-两个数组元素一样,位置个数不相同,按照一个标准的列表实现另一个列表的排序
    XORM高级操作
    flutter踩坑指南 配置篇
    create-react-app项目暴露webpack配置文件
  • 原文地址:https://www.cnblogs.com/vanwoos/p/4821744.html
Copyright © 2011-2022 走看看