#include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <iostream> #include <cstring> using namespace std; #define PATH_NAME "/tmp/shm_mark" int main(int, char**) { int fd; fd = open(PATH_NAME, O_CREAT, 0666); if(fd < 0) { cout << "open file" << PATH_NAME << "failed, with errno:" << strerror(errno) << endl; return -1; } close(fd); key_t key = ftok(PATH_NAME, 0); int shm_ref_id; shmid_ds shm_info; int ret = 0; shm_ref_id = shmget(key, sizeof(int), IPC_CREAT | 0666 | IPC_EXCL); if(shm_ref_id < 0 ) { cout << "shmget failed.." << strerror(errno) << endl; return -1; } cout << "shmget id:" << shm_ref_id << endl; // char *shmaddr = (char*)shmat(shm_ref_id, NULL, 0); // shmdt(shmaddr); ret = shmctl(shm_ref_id, IPC_RMID, 0);//&shm_info); cout << "shmctl ret:" << ret << endl; if(ret < 0) { cout << "shmctl errno:" << errno << endl; return -1; } cout << "shm key:0x" << hex << key << dec << endl; cout << "shm id:" << shm_ref_id << endl; cout << "shm segsz:" << shm_info.shm_segsz << endl; cout << "shm nattch:" << shm_info.shm_nattch << endl; return 0; }
0666:設置的是共享內存的權限。html
IPC_CREAT:若發現沒有對應的共享內存建立對應指定key_t類型ipc鍵的共享內存。linux
IPC_RMID:移除指定shm_id的共享內存。ios