shmat返回分段falut与errno = 13(EACCES)

我只想测试shmget()和shmat(),但似乎有些不对劲。 🙁

shmget()运行良好,但shmat()导致分段错误。

这是代码:

#include  #include  #include  #include  #include  int main(void) { key_t key=98;/* yes, just 98 for test */ int shid; char *str=NULL; shid = shmget(key, 4096, IPC_CREAT); printf("shid:%d\n",shid); str=(char*)shmat(shid,NULL,0); printf("str:%d\n",(int)str); printf("errno:%d\n", errno); str[0] = 'h'; str[1] = '\0'; return 0; } 

这是输出:

 shid:28246036 str:-1 errno:13 zsh: segmentation fault ./t1 

thx:D

您必须在开始时定义_SVID_SOURCE_XOPEN_SOURCE

 #define _SVID_SOURCE #include  #include  ... 

使用ftok()创建key

 key_t key= ftok("demo.c", 'R'); 

它返回errno 13因为你没有设置PERMS:

 shid = shmget(key, 4096, IPC_CREAT); 

一定是

 shid = shmget(key, 4096, 0777 | IPC_CREAT);