Search code examples
cmemoryipcshared

How to properly use shmget & shmat for IPC Shared Memory use case


I tried understand the behavior of the following code

int memoryId = shmget(1234, 10240, IPC_CREAT | 0666);
client *client1 = shmat(memoryId, NULL, 0);
bool *game = shmat(memoryId, NULL, 0);
*game = true;
printf("1Game: %s\n",(*game)?"true":"false");
printf("2Game: %s\n",(*game)?"true":"false");
*client1 = (client){ 0, 0, 0, 0, 0, 0, 300, false};
printf("3Game: %s\n",(*game)?"true":"false");

Here is the output:

1Game: true
2Game: true
3Game: false

I do not understand why the output when getting to 3Game line is changed.

Any suggestion on how do shmget & shmat work?


Solution

  • shmget()

    shmget() returns the identifier of the System V shared memory segment associated with the value of the argument key.

    shmat()

    shmat() attaches the shared memory segment identified by shmid to the address space of the calling process.

    basically shmget creates a shared memory buffer IPC_CREAT and returns it's ID. shmat attaches the memory buffer to your application and returns a pointer to it.

    since both game and client1 use shmat to the same shared buffer, the corrosponding pointer is the same.

    considering this:

    *game = true;
    *client1 = (client){ 0, 0, 0, 0, 0, 0, 300, false};
    

    both lines set values to the same location in memory - hence the result you got is as expected

    http://man7.org/linux/man-pages/man2/shmget.2.html

    https://linux.die.net/man/2/shmat