C 中的共享内存:Shmget 问题
Shared Memory in C: Shmget Issues
int shmid;
int* locat;
//create shared memory segment
shmid = shmget(6666, size, 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
locat = (int *) shmat(shmid, NULL, 0);
if (locat == (int *) -1) {
perror("shmat");
exit(1);
}
我正在这样设置共享内存,但我一直收到此错误:shmget: No such file or directory
这段代码工作正常,不知道为什么现在会这样。
IPC_CREAT
Create a new segment. If this flag is not used, then shmget()
will find the segment associated with key and check to see if the user has permission to access the segment.
您必须将 IPC_CREAT
添加到您的 shmget
通话中
shmid = shmget(6666, size, IPC_CREAT | 0666);
您还可以使用 IPC_EXCL
来确保该段是新创建的
IPC_EXCL
This flag is used with IPC_CREAT
to ensure that this call
creates the segment. If the segment already exists, the
call fails.
有两件事:
- 当你想初始化一个共享内存(对应于一个特定的键值)时,你必须将权限号与IPC_CREAT.
进行位或运算。
喜欢
shmget(6666 , size , 0666|IPC_CREAT);
- 当您想将同一段(由键值标识)附加到另一个进程时,IPC_CREAT 不是必需的,因为共享内存已经在逻辑地址 space 上创建。
int shmid;
int* locat;
//create shared memory segment
shmid = shmget(6666, size, 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
locat = (int *) shmat(shmid, NULL, 0);
if (locat == (int *) -1) {
perror("shmat");
exit(1);
}
我正在这样设置共享内存,但我一直收到此错误:shmget: No such file or directory
这段代码工作正常,不知道为什么现在会这样。
IPC_CREAT
Create a new segment. If this flag is not used, then
shmget()
will find the segment associated with key and check to see if the user has permission to access the segment.
您必须将 IPC_CREAT
添加到您的 shmget
通话中
shmid = shmget(6666, size, IPC_CREAT | 0666);
您还可以使用 IPC_EXCL
来确保该段是新创建的
IPC_EXCL
This flag is used with
IPC_CREAT
to ensure that this call creates the segment. If the segment already exists, the call fails.
有两件事:
- 当你想初始化一个共享内存(对应于一个特定的键值)时,你必须将权限号与IPC_CREAT. 进行位或运算。
喜欢
shmget(6666 , size , 0666|IPC_CREAT);
- 当您想将同一段(由键值标识)附加到另一个进程时,IPC_CREAT 不是必需的,因为共享内存已经在逻辑地址 space 上创建。