下面我们先来通过一段程序来 初步了解一下如何使用共享内存实现进程间通信
首先编写公共的头文件comm.h
#ifndef _COMM_
#define _COMM_
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<unistd.h>
#define PATHNAME "."
#define PROJ_ID 0x666
int create_shm(int size);
int get_shm();
int destroy_shm(int shmid);
#endif
接下来是接口实现的源文件
#include"comm.h"
static int comm_shm(int size, int flags)
{
key_t key = ftok(PATHNAME, PROJ_ID);
if(key < 0)
{
perror("ftok");
return -1;
}
int shmid = shmget(key,size,flags);//共享内存创建函数
if(shmid < 0)
{
perror("shmget");
return -2;
}
return shmid;
}
int create_shm(int size)
{
return comm_shm(size,IPC_CREAT | IPC_EXCL);
}
int get_shm()
{
return comm_shm(0,IPC_CREAT);
}
int destroy_shm(int shmid)
{
if(shmctl(shmid,IPC_RMID,NULL) < 0)//共享内存销毁函数
{
perror("shmctl");
return -1;
}
return 0;
共享内存实现进程间通信
最新推荐文章于 2024-07-12 21:30:00 发布