共享内存出错:shmid: 0  shmat 1: Invalid argument

小魔菇 2009-05-27 03:43:03

#include ...
#define SHM_KEY 100
#define SHM_SIZE 1024
int main(int argc,char *argv[])
{
int shmid;
void *shmaddr1,*shmaddr2,*shmaddr3;
if((shmid=shmget(SHM_KEY,SHM_SIZE,IPC_CREAT|0660))==-1)
{
perror("shmget");
exit(-1);
}

printf("shmid: d\n",shmid);
if((shmaddr1=shmat(shmid,0,0))==-1)
{
perror("shmat 1");
exit(-1);
}
printf("shaddr1:0x.8x\n",shmaddr1);

if(shmaddr2=shmat(shmid,0,0)==-1)
{
perror("shmat 2");
exit(-1);
}
printf("shaddr2:0x.8x\n",shmaddr2);
while(1);
return 0;
}

运行结果:
shmid: 0
shmat 1: Invalid argument

我知道大部分情况下程序是可以正常运行的 
不会出现上述的结果
我也不知道当时电脑不知道设置了什么 
或者 什么条件不满足就出现了这种情况
现在就是想找出原因 
期待碰到这种情况的高手指点一下
...全文
1437 15 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
expresscool 2010-09-26
  • 打赏
  • 举报
回复
HP 上对同一个共享内存段只能一次shmat 必须执行完shmdt后才可以再次shmat ,映射两次有什么用呢?
datacode 2009-05-27
  • 打赏
  • 举报
回复
    if((shmid=shmget(SHM_KEY,SHM_SIZE,IPC_CREAT|0660))==-1) 
{
perror("shmget");
exit(-1);
}


改为:

    if((shmid=shmget(SHM_KEY,SHM_SIZE,IPC_CREAT|0660)) < 0) 
{
perror("shmget");
exit(-1);
}
  • 打赏
  • 举报
回复
if((shmid=shmget(SHM_KEY,SHM_SIZE,IPC_CREAT|0660))==-1)


标识符SHM_KEY为何不用ftok获取。而是直接宏定义呢?
虽然我也一直不清楚,ftok的作用,你还是先改了试试。
goodname 2009-05-27
  • 打赏
  • 举报
回复
一般就是EINVAL,其实从系统的头文件里面也可以找到,一般有个errno.h


小魔菇 2009-05-27
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 goodname 的回复:]
可以取errno,看看错误码是多少,然后查手册。。。。。
[/Quote]

查什么手册?
22号错误 咋个查呢?
linren 2009-05-27
  • 打赏
  • 举报
回复
看不出有什么特别的问题来
可以试一试:
if(shmaddr1=shmat(shmid,0,0)==(char*)-1)

最好用:
shmaddr2=shmaddr1
goodname 2009-05-27
  • 打赏
  • 举报
回复
可以取errno,看看错误码是多少,然后查手册。。。。。
小魔菇 2009-05-27
  • 打赏
  • 举报
回复
情况是这样的
一个进程创建了一个共享内存
其他的进程来shmget,然后shmat到一个固定的地址空间
大小和flag都是一样的
但是有时候就出现上述的错误 有时候就没事
goodname 2009-05-27
  • 打赏
  • 举报
回复

if((shmaddr1=shmat(shmid,0,SHM_RDONLY))==-1)

试试
小魔菇 2009-05-27
  • 打赏
  • 举报
回复
没办法单步
因为我无法调试源码
只能猜测了
只能寄望于见过这种情况的高手了 
小魔菇 2009-05-27
  • 打赏
  • 举报
回复
你的意思是共享内存地址的对齐或者是边界的原因?
冷月清晖 2009-05-27
  • 打赏
  • 举报
回复
单步一下吧。
冷月清晖 2009-05-27
  • 打赏
  • 举报
回复
shmat 函数贴出来看看。
goodname 2009-05-27
  • 打赏
  • 举报
回复
ERRORS

The shmat() function shall fail if:

[EACCES]
Operation permission is denied to the calling process; see XSI Interprocess Communication.
[EINVAL]
The value of shmid is not a valid shared memory identifier, the shmaddr is not a null pointer, and the value of (shmaddr -((uintptr_t)shmaddr %SHMLBA)) is an illegal address for attaching shared memory; or the shmaddr is not a null pointer, (shmflg &SHM_RND) is 0, and the value of shmaddr is an illegal address for attaching shared memory.
[EMFILE]
The number of shared memory segments attached to the calling process would exceed the system-imposed limit.
[ENOMEM]
The available data space is not large enough to accommodate the shared memory segment.

从描述上来看,像EINVAL
wwoo_1105 2009-05-27
  • 打赏
  • 举报
回复
帮顶

70,024

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧