尝试附加共享内存的已用地址时出错
使用 shmget 且第二个参数不为 NULL 时收到消息“Invalid argument”。
它编译正常,但是在执行时,我收到此错误消息。
我一整天都被这个问题困住了。希望你能帮助我! :)
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int idSharedMem;
int *varSharedMem1;
int *varSharedMem2;
/* Create the shared memory */
idSharedMem = shmget((key_t) 0001, sizeof(int), IPC_CREAT | 0666);
if (idSharedMem == -1)
{
perror("shmget");
}
/* Allocate a memory address and attached it to a variable */
varSharedMem1 = shmat(idSharedMem, NULL, 0);
if (varSharedMem1 == (int *) -1)
{
perror("shmat1");
}
/* Sign a value to the variable */
*varSharedMem1 = 5;
/* Attach an existing allocated memory to another variable */
varSharedMem2 = shmat(idSharedMem, varSharedMem1, 0);
if (varSharedMem2 == (int *) -1)
{
/* PRINTS "shmat2: Invalid argument" */
perror("shmat2");
}
/* Wanted it to print 5 */
printf("Recovered value %d\n", *varSharedMem2);
return(0);
}
Receiving the message "Invalid argument" when using shmget with the second parameter not being NULL.
It compiles ok, but when executing, I get this error message.
I've been stuck on this all day long. Hope you can help me! :)
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int idSharedMem;
int *varSharedMem1;
int *varSharedMem2;
/* Create the shared memory */
idSharedMem = shmget((key_t) 0001, sizeof(int), IPC_CREAT | 0666);
if (idSharedMem == -1)
{
perror("shmget");
}
/* Allocate a memory address and attached it to a variable */
varSharedMem1 = shmat(idSharedMem, NULL, 0);
if (varSharedMem1 == (int *) -1)
{
perror("shmat1");
}
/* Sign a value to the variable */
*varSharedMem1 = 5;
/* Attach an existing allocated memory to another variable */
varSharedMem2 = shmat(idSharedMem, varSharedMem1, 0);
if (varSharedMem2 == (int *) -1)
{
/* PRINTS "shmat2: Invalid argument" */
perror("shmat2");
}
/* Wanted it to print 5 */
printf("Recovered value %d\n", *varSharedMem2);
return(0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
shmat(idSharedMem, varSharedMem1, 0);
,您尝试将段附加到varSharedMem1
的位置。但是,您之前已在该位置附加了一个段,这将导致 EINVAL。 Linux 提供了 SHM_REMAP 标志,您可以使用它来替换以前映射的段。shmat 联机帮助页:
With
shmat(idSharedMem, varSharedMem1, 0);
you're trying to attach the segment at the location ofvarSharedMem1
. However you have previously attached a segment at that location which will result in EINVAL. Linux provides a SHM_REMAP flag you can use to replace previously mapped segments.shmat manpage:
来自 shmat 手册页:
更多来自 shmat 手册页:
要进行第二个附加,只需:
From shmat man page:
more from shmat man page:
To make a second attach, just: