如何为 IPC 共享内存用例正确使用 shmget 和 shmat

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

我试着理解以下代码的行为

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

这是输出:

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

我不明白为什么到3Game线时的输出改变了。

关于 shmget 和 shmat 如何工作有什么建议吗?

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.

基本上shmget 创建一个共享内存缓冲区IPC_CREAT 和returns 它的ID。 shmat 将内存缓冲区附加到您的应用程序并 returns 指向它的指针。

因为gameclient1都使用shmat到同一个共享缓冲区,所以相应的指针是相同的。

考虑到这一点:

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

这两行都将值设置到内存中的相同位置 - 因此您得到的结果符合预期

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

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