Linux下共享内存学习笔记(三)
1. 共享内存编程思路
一个进程写数据,一个进程读数据
-
写进程:
-
shmget()获取共享内存
-
shmat()共享内存映射到进程空间
-
-
写数据
- 读进程:
- shmget()获取共享内存
- shmat()共享内存映射到进程空间
- 读进程:
-
读数据
- shmdt()共享内存从进程空间解除映射
- shmctl()删除共享内存
2. 历程
- 读进程
// Created by gxf on 2020/2/10.
#ifndef UNTITLED_MAIN_H
#define UNTITLED_MAIN_H
char *ftokFilePath = "/Users/gxf/CLionProjects/untitled/main.c";
int project_id = 10;
typedef struct
{
int age;
char name[50];
}person;
#endif //UNTITLED_MAIN_H
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include "main.h"
int main()
{
key_t ftokRes = ftok(ftokFilePath, project_id);
person *zhangsan;
person lisi = {10, "lisi"};
int shmid = shmget(ftokRes, sizeof(person), IPC_CREAT | 0777);
printf("shamid :%d\n", shmid);
zhangsan = (person *)shmat(shmid, NULL, SHM_W);
zhangsan->age = 20;
strcpy(zhangsan->name, "zhangsan1111");
return 0;
}
// Created by gxf on 2020/2/10.
#include <stdlib.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include "main.h"
int main()
{
key_t ftokRes = ftok(ftokFilePath, project_id);
printf("%d\n", ftokRes);
person *zhangsan = malloc(sizeof(person));
int shmid = shmget(ftokRes, sizeof(person), IPC_CREAT);
person *shmaddr = shmat(shmid, NULL, SHM_R);
memcpy(zhangsan, shmaddr, sizeof(person));
printf("age:%d, name:%s\n", zhangsan->age, zhangsan->name);
int res = shmdt(shmaddr);
if (res)
fprintf(stderr, "shmdt fail");
res = shmctl(shmid, IPC_RMID, NULL);
if (res)
fprintf(stderr, "rm ipcs -m fail");
return 0;
}