这是关于 LINUX 中的共享内存

This is regarding shared memory in LINUX

#include<sys/shm.h>
#include<sys/stat.h>
#include<stdio.h>
int main(void)
{
int segment_id;
char *shared_memory;
const int size=4069;
segment_id=shmget(IPC_PRIVATE,size,S_IRUSR|S_IWUSR);
printf("segment ID=%d\n",segment_id);
shared_memory=(char *)shmat(segment_id,NULL,0);
sprintf(shared_memory,"Hi There!");
while(1){
}
return 0; 

}

如果在下面的程序中输入相同的segment_id,可以吗?

#include<sys/shm.h>
#include<sys/stat.h>
#include<stdio.h>
int main(void)
{
int segment_id;
char *shared_memory;
const int size=4069;
printf("please input segment id\n");
scanf("%d",&segment_id);
shared_memory=(char *)shmat(segment_id,NULL,0);
printf("%s\n",shared_memory );
return 0;
}

它在这里工作,但请解释它是如何工作的,这意味着 segment_id 在下面的程序中也是如何工作的?

您正在使用 System V 共享内存,这是操作系统提供的一项功能。

shmget(2) 手册的第一行说,

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

shmat(2) 手册的第一行说,

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

使用 shmget,您提供一个密钥,它 returns 一个标识符。使用 shmat,您提供该标识符,它 returns 是您可以使用的地址。这有什么好困惑的?

我怀疑你和我第一次遇到它时一样感到惊讶。与大多数系统资源(文件描述符、套接字等)不同,共享内存段在程序终止时不会被释放。它们保留在那里,随时可以在程序提供适当的标识符时重新使用。

您甚至不需要编写程序来查看它们。看看 ipcs(1) 和 ipcrm(1)。

如果您考虑一下,对于某些应用程序,它们必须是持久的。 Berkeley 的替代方案 mmap(2) 使用文件名来实现相同的目的。