简单记录新建读写共享内存的小笔记,实际项目中需要对操作进行细化
一、写入端
#include<stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#define BUF_SIZE 1024
int main(void)
{
int shmid;
char *shmptr;
key_t key;
char buf_data[1024]="hello world";
if ((key = ftok("/home", 200)) == -1) {
perror("ftok error");
}
if((shmid = shmget(key,BUF_SIZE,IPC_CREAT|0666)) ==-1)
{
printf("shmget error \n");
exit(1);
}
if((shmptr =shmat(shmid,0,0))==(void *)-1)
{
printf("shmat error!\n");
exit(1);
}
memcpy(shmptr,buf_data,sizeof(buf_data));
return 0;
}
二、读出数据端
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 1024
int main(int args, char *argv[]) {
int shmid;
int ret;
key_t key;
char *shmadd;
// 创建key值
if ((key = ftok("/home", 200)) == -1) {
perror("ftok faild");
return 0;
}
// 打开共享内存
if ((shmid = shmget(key, BUFFSIZE, IPC_CREAT|0666)) < 0) {
perror("shmget faild");
exit(-1);
}
// 映射
if ((shmadd = shmat(shmid, NULL, 0)) < 0) {
perror("shmat faild");
exit(-1);
}
// 读取共享内存中的数据
printf("get data = %s\n", shmadd);
// 分离共享内存和当前进程
if ((ret = shmdt(shmadd)) < 0) {
perror("shmdt faild");
} else {
printf("Delete shared-memory sucess\n");
}
// 删除共享内存
shmctl(shmid, IPC_RMID, NULL);
return 0;
}