- 论坛徽章:
- 2
|
weishuo1999 发表于 2015-03-02 17:55
你看看你create的时候的权限是什么,还有是不是root创建的,另外可以打一下错误信息,strerror函数看看就知 ...
ftok的参数是"s",这个是我用普通用户创建的一个空文件。
我按照你说的,加了对errno的打印,发现错误代码是13,代码如下:
- #include<errno.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<fcntl.h>
- #include<sys/ipc.h>
- #include<sys/shm.h>
- #include<sys/types.h>
- #include<sys/wait.h>
- #include<assert.h>
- int main()
- {
- key_t k=ftok("s",'1');
- pid_t id=fork();
- if(id==0)//
- {
- printf("child begin\n");
- int fd=shmget(k,1000,IPC_CREAT);
- assert(fd!=-1);
- void* p=shmat(fd,NULL,0);
- printf("shmat OK\n");
- long res = (long)p;
- if(res<0)
- {
- printf(" res < 0 error = %d\n", errno);
- return 0;
- }
- int* pi=(int*)p;
- *pi=2;
- printf("child ends\n");
- shmdt(p);
- }
- else if(id>0)//father
- {
- printf("father begin\n");
- int status;
- wait(&status);
- int fd=shmget(k,1000,IPC_CREAT);
- assert(fd!=-1);
- void* p=shmat(fd,NULL,0);
- printf("shmat OK\n");
- long res = (long)p;
- if(res<0)
- {
- printf(" res < 0 error = %d\n", errno);
- return 0;
- }
- int *pi=(int*)p;
- printf("pi=%d\n",*pi);
- printf("father ends\n");
- shmdt(p);
- }
- return 0;
- }
复制代码 普通用户的运行输出如下:
- father begin
- child begin
- shmat OK
- res < 0 error = 13
- shmat OK
- res < 0 error = 13
复制代码 |
|