简体   繁体   中英

IPC using shared memory

I am writing a simple code in which parent and child process are sharing one queue using shared memory method. But when child process modifies the shared data its somehow not reflecting for parent process and parent process is still accessing the previous value. where I am attaching a sample code what I am trying to do:

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;
}

Thanks in advance!

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

You're trying to create 2 seperate variables with same shared memory id.

try using 2 keys and 2 shared memorys.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM