Linux c 共享内存
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int islock;
} VMMSHM;
int deleteShareMem() {
int shm_id;
key_t key;
key = ftok("vmmshm", 1); // 计算标识符
shm_id = shmget(key, 4096, IPC_CREAT);
if (shmctl(shm_id, IPC_RMID, NULL) == -1)
return -1;
return 1;
}
int isLocked() {
int shm_id;
key_t key;
VMMSHM *p_map;
int islock;
key = ftok("vmmshm", 1); // 计算标识符
shm_id = shmget(key, 4096, IPC_CREAT);
printf("shmid:%d\n", shm_id);
if (shm_id == -1) {
perror("shmget error");
return -1;
}
p_map = (VMMSHM*) shmat(shm_id, NULL, 0);
islock = p_map->islock;
if (shmdt(p_map) == -1) {
perror("shmdt error\n");
return -1;
}
return islock;
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int islock;
} VMMSHM;
int deleteShareMem() {
int shm_id;
key_t key;
key = ftok("vmmshm", 1); // 计算标识符
shm_id = shmget(key, 4096, IPC_CREAT);
if (shmctl(shm_id, IPC_RMID, NULL) == -1)
return -1;
return 1;
}
int isLocked() {
int shm_id;
key_t key;
VMMSHM *p_map;
int islock;
key = ftok("vmmshm", 1); // 计算标识符
shm_id = shmget(key, 4096, IPC_CREAT);
printf("shmid:%d\n", shm_id);
if (shm_id == -1) {
perror("shmget error");
return -1;
}
p_map = (VMMSHM*) shmat(shm_id, NULL, 0);
islock = p_map->islock;
if (shmdt(p_map) == -1) {
perror("shmdt error\n");
return -1;
}
return islock;
}
int setLocked()
{
int shm_id;
key_t key;
VMMSHM *p_map;
key = ftok("vmmshm", 1);
shm_id = shmget(key, 4096, IPC_CREAT);
printf("shmid:%d\n",shm_id);
if (shm_id == -1)
{
perror("shmget error \n");
return -1;
}
p_map = (VMMSHM*) shmat(shm_id, NULL, 0);
p_map->islock = 1;
if (shmdt(p_map) == -1) {
perror("detach error");
return -1;
}
return 1;
}
//用ipcs -m命令查看系统的所有共享内存
躲猫猫社团团长 http://t.sina.com.cn/coolria