对于UNIX / C项目,我应该分别为两个整数分配两个共享内存段(子进程最终将分别以只读和写权限访问)。但是每当我尝试调用shmat(3)时,它最终返回-1,将errno设置为EACCES,显然表明权限不足。我已经为下面的错误生成了似乎所需的最小代码,可能还有一些额外的包含:
#define _SVID_SOURCE
#include <errno.h>
#include <stdio.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int i, j, shmid, tshmid;
int * clock;
int * shmMsg;
tshmid = shmget(IPC_PRIVATE,sizeof(int)*2, IPC_CREAT | IPC_EXCL | 0777); //0777 permissions are more liberal than I need, but I've tried other various literals and numbers as well as just CREAT/EXCL.
if (tshmid < 1){
printf("Error: In parent process (%d), shmid came up %d \n",getpid(),shmid);
exit(-1);
}
clock = (int *) shmat(shmid,NULL,0); //I've also tried this with the second argument as (void *) 0, and with the third argument as "(SHM_R | SHM_W)" and "0777"
if (clock == (void *) -1){
printf("Error: First shmat couldn't shmattach to shmid #%d. ERRNO %d\n",shmid,errno);
shmdt(clock);
exit(-1);
} //it never even gets this far
shmdt(clock);
}
每次都会产生如下错误消息:
错误:第一个shmat无法shmattach shmid#1033469981。 ERRNO 13
我的程序的较长版本最初返回相同的错误,但是errno设置为43(EIDRM:由shm_id标识的段被删除)。我已经递归地将整个目录chmodded到完全访问权限,所以这不是问题,每次我的程序崩溃时我都必须使用ipcrm手动释放共享内存,因此shmids适用于实际的段。为什么不附上?