共享内存给结果带来歧义

时间:2019-01-06 10:24:31

标签: linux shared-memory

我试图使用共享内存概念在两个进程之间进行通信。但是在这里,尽管我已经将不同变量的共享内存地址指向了不同的文件,但是它们似乎是相连的。一旦我更改了一个变量的值,新值也将覆盖另一个变量,在这种情况下,se1-> val和se2-> val即将连接起来。有人可以帮忙为什么会这样吗?

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#define s(t) scanf("%d",&t)
#define p(t) printf("%d ",t)
struct sem
{
    int val;
    int xy;
};
struct sem* se1;
struct sem* se2;
int main()
{
    printf("You in P1\n");
    key_t key1,key2;
    key1=ftok("shmfile1",0);
    key2=ftok("shmfile3",0);
    int shmid1=shmget(key1, sizeof(struct sem),0644|IPC_CREAT);
    int shmid2=shmget(key2, sizeof(struct sem),0644|IPC_CREAT);
    se1=shmat(shmid1,NULL,0);
    se2=shmat(shmid2,NULL,0);
    se1->xy=4;
    se2->xy=8;
    se1->val=0;
    se2->val=1;
    int r=10;
    while(r--)
    {
        printf("\nIn P1 process ");
        while(se2->val==0);
        se2->val--;
        se1->xy=se2->xy+1;
        se1->val++;
        p(se1->xy);
        p(se2->xy);
    }
    return 0;
}

预计se1-> val和se2-> val会导致信号量类型的结果,但是由于覆盖,它不会发生!

0 个答案:

没有答案