SYSTEM V标准的共享内存用于进程间通信的权限管理示例

 

输出同现SEGMENTATION FAULT是因为试图写操作,这是因为将虚拟内存挂载为了READ ONLY方式导致的权限不够。

 1 #include <sys/shm.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <stdio.h>
 5 #include <sys/ipc.h>
 6 #include <string.h>
 7 
 8 int main(int argc, char *argv[])
 9 {
10     key_t key;
11     int shm_id;
12     char *ptr;
13     key = ftok("/", 10);
14     shm_id = shmget(key, 100, IPC_CREAT | SHM_R);
15     printf("get the share memory id is %d\n", shm_id);
16     if((ptr = (char *)shmat(shm_id, NULL, SHM_RDONLY)) == NULL)
17     {
18         if(shmctl(shm_id, IPC_RMID, NULL) == -1)
19             perror("Failed to remove memory segment");
20             exit(EXIT_FAILURE);
21     }
22     printf("in yangzd the attach add is %p\n", ptr);
23     printf("Now ,try to write the memory.\n");
24     *ptr = 'd';
25     printf("*ptr = %c\n", *ptr);
26     shmdt(ptr);
27     shmctl(shm_id, IPC_RMID, 0 );
28 }

输出:
 ./shmat_rd_flag_regular
get the share memory id is 32769
in yangzd the attach add is 0xb7734000
Now ,try to write the memory.
Segmentation fault

查看当前系统的共享内存信息,可以看到新建的共享内存段:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值