C在具有活动等待的子进程之间共享内存时出错

时间:2016-04-14 16:15:14

标签: c shared-memory

我正在尝试使用子进程和父进程之间的共享内存来执行程序。该程序也使用分叉。

演习的目的是: -Father发送给孩子(带有共享内存)3次带有活动等待的向量

-Child接收vec,打印并更改同步变量

  Struct:
    typedef struct{
    int change[NUM_TOTAL];
    int synchronize;
    }Exchange; 
Exchange *vec;

int fd = shm_open("/shmtest8",O_CREAT| O_RDWR,S_IRUSR|S_IWUSR); 
//Check shm_open error
ftruncate(fd, 100);
vec = (Exchange*)  mmap(NULL,100,PROT_READ|PROT_WRITE, MAP_SHARED, fd ,0);      

     x = forkFunc()  //Creates a fork, and return 0 to parente and > 0 to child process
    if(x == 0){  //Parent
    int cont = 0;

    while(cont != 3){
        printf("Father\n");
        vec->synchronize = 1;  //Now go to to the child

        while(vec->synchronize!=0); //the child change the variable to 0                
        cont++;
        printf("cont %d",cont);
    }


    wait(NULL);

    munmap(vec,sizeof(vec));
    close(fd);
    shm_unlink("/shmtest8");


}else if(x > 0){   //Child

    int cont = 0;

        while(vec->synchronize!=1);   //Exit while when father change the variable to 1
        int i;

    for(i = 0; i < 10; i++){
            printf("%d\t",i);
        }

        vec->synchronize =0;    //Return to the father
}   

以下是输出的例子:

     Father
     Child
      0 1   2   3   4   5   6   7   8   9
     cont 1
     Father

在第一次迭代之后,程序在“while(vec-&gt; synchronize!= 0)”之后冻结;“ ...我猜这个问题存在于儿童过程中,但我不知道为什么......任何想法?

谢谢

3 个答案:

答案 0 :(得分:3)

我认为你的子进程部分应该还有1个循环

while(cont != 3){
     while(vec->synchronize!=1);   //Exit while when father change the variable to 1
     int i;
     for(i = 0; i < 10; i++){
          printf("%d\t",i);
     }

     ec->synchronize =0;    //Return to the father
     cont++
 }

答案 1 :(得分:1)

不知道副手,但我可以告诉你,任何时候两个线程写入同一个变量(vec->synchronize),你就会遇到麻烦。对于这样的同步,请允许我推荐管道或semaphores。仅当一个线程写入时,或者当您使用其他机制(如信号量或互斥锁)来控制对共享内存的访问时,才使用共享内存。

答案 2 :(得分:1)

如果您不能使用信号量,请改用信号和信号处理程序。如果你不能使用信号,我可以看到另外两个解决方案:

  1. 当代码处于关键区域时(修改共享内存),使用掩码阻止所有信号。这样就可以确保数据共享内存没有损坏。

  2. 您应该使用原子函数,例如Test&amp; Set,而不是while(vec->synchronize!=1)。这个问题在于很难用软件实现。

  3. 现在,这些已经不太好的解决方案的最大缺点是,它们不适用于多处理器系统。

相关问题