IPC使用共享内存

时间:2012-02-16 17:15:54

标签: c ipc shared-memory

我正在编写一个简单的代码,其中父进程和子进程使用共享内存方法共享一个队列。但是当子进程修改共享数据时,它以某种方式不反映父进程,而父进程仍在访问先前的值。 在哪里我附上我想要做的示例代码:

int main()
{
    /* Declare fork variables */
    pid_t childpid;

    /* Declare shared memory variables */
    key_t key;
    int shmid;
    int *front;
    int *rear;
    int i;
    /* Declare semaphore variables */
    sem_t sem;
    int pshared = 1;
    unsigned int value = 1;

    /* Initialize Shared Memory */
    key = ftok("thread1.c",'R');
    shmid = shmget(key, 1024, 0644 | IPC_CREAT);

    /* Attach to Shared Memory */
    rear = shmat(shmid, (void *)0, 0);
    if(rear == (int *)(-1))
        perror("shmat");

    front = shmat(shmid, (void *)0, 0);
    if(front == (int *)(-1))
        perror("shmat");

    /* Write initial value to shared memory */
    rear= front;
    /* Write to Shared Memory */
    for(i=0; i<5; i++)
    {
        rear[i] = 5000+(i+1);
    }
    printf("value of front is: %d", *front);
    rear = &rear[i-1];  
    /* Initialize Semaphore */
    if((sem_init(&sem, pshared, value)) == 1)
    {
        perror("Error initializing semaphore");
        exit(1);
    }

    if((childpid = fork()) < 0) // error occured
    {
        perror("Fork Failed");
        exit(1);
    }
    else if(childpid == 0) // child process
    {
        printf("came in child process\n");
        sem_wait(&sem);
        for(i=0; i<3; i++){
            printf("rear is: %d", *rear);
            rear--;
        }
        sem_post(&sem);
        shmdt(rear);

    }
    else // parent process
    {
        /* Write to Shared Memory */
        wait(1);
        sem_wait(&sem);
        printf("came in parent process and rear is: %d\n", *rear);
        sem_post(&sem);
        shmdt(rear);
    }
    return 0;
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

rear = shmat(shmid, (void *)0, 0);
front = shmat(shmid, (void *)0, 0);

您正在尝试使用相同的共享内存ID创建2个单独的变量。

尝试使用2个键和2个共享记忆。

key1  = ftok("thread1.c",'A');
key2  = ftok("thread1.c",'B');
shmid1 = shmget(key, 1024, 0644 | IPC_CREAT);
shmid2 = shmget(key, 1024, 0644 | IPC_CREAT);
rear = shmat(shmid1, (void *)0, 0);
front = shmat(shmid2, (void *)0, 0);