输出同现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
查看当前系统的共享内存信息,可以看到新建的共享内存段:
时间: 2024-10-27 15:34:19