我只想测试shmget()和shmat(),但似乎有些不对劲。 :(
shmget()效果很好但是shmat()会导致分段错误。
这是代码:
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <errno.h>
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
答案 0 :(得分:3)
您必须在最开始时定义_SVID_SOURCE
或_XOPEN_SOURCE
#define _SVID_SOURCE
#include <stdlib.h>
#include <sys/ipc.h>
...
使用key
ftok()
key_t key= ftok("demo.c", 'R');
它返回errno 13
,因为您没有设置PERMS:
shid = shmget(key, 4096, IPC_CREAT);
必须是
shid = shmget(key, 4096, 0777 | IPC_CREAT);