linux c之shm共享内存的使用例子

//shm_test.c
#include 
#include 
#include 

#define BUFFERSIZE 1024
int main(int argc, char const *argv[])
{
	int shmid;
	char* shmadd;
	//创建一个共享内存对象
	if((shmid=shmget(IPC_PRIVATE,BUFFERSIZE,0666))<0)
	{
		perror("shmget error");
		exit(-1);
	}else{
		printf("create shared memory:%d\n",shmid);
	}
	system("ipcs -m");
	//挂载共享内存到进程中
	if((shmadd=shmat(shmid,0,0))<(char*)0)
	{
		perror("shmat error");
		exit(-1);
	}else{
		printf("attached shared memory\n");
	}
	system("ipcs -m");
	//卸载共享内存
	if(shmdt(shmadd)<0)
	{
		perror("shmdt error");
		exit(-1);
	}else{
		printf("deleted shared memory\n");
	}
	system("ipcs -m");
	//完成对共享内存的控制,释放共享内存
	//IPC_RMID:删除这片共享内存
	if(shmctl(shmid,IPC_RMID,0)<0)
	{
		perror("shmctl error");
		exit(-1);
	}
	printf("release shared memory\n");
	exit(0);

	return 0;
}

//shm_server.c
#include 
#include 
#include 
#include 
#include //ipc
#include 
#include 

struct sys_data
{
	float data_rh;
	float data_t;
};

//基于课程http://edu.51cto.com/lesson/id-131448.html
//linux c之shm共享内存的使用例子
int main(int argc, char const *argv[])
{
	void* shm=(void*)0;
	int shmid;
	struct sys_data *da;
	float ftemp=0.0,fhumi=0.0;
	//set share memory;
	//linxu可以使用ipcrm -m shmid 删除此共享内存。
	//创建一个共享内存对象
	shmid=shmget((key_t)8891,sizeof(struct sys_data),0666|IPC_CREAT);
	if(shmid==-1)
	{
		printf("shmget error\n");
		exit(-1);
	}else{
		printf("server shmid=%d\n", shmid);
	}
	//把共享内存映射到调用进程的地址空间
	//挂载共享内存到进程中
	shm=shmat(shmid,(void*)0,0);
	if(shm==(void*)(-1))
	{
		printf("shmat error\n");
		exit(-1);
	}
	da=shm;
	printf("shmat start\n");
	while(1)
	{
		ftemp=rand()%100;
		fhumi=rand()%100;
		da->data_t=ftemp;
		da->data_rh=fhumi;
		sleep(1);
	}

	return 0;
}

//shm_client.c
#include 
#include 
#include 
#include 
#include //ipc
#include 
#include 

struct sys_data
{
	float data_rh;
	float data_t;
};

int main(int argc, char const *argv[])
{
	void* shm=(void*)0;
	int shmid;
	struct sys_data *da;
	float ftemp=0.0,fhumi=0.0;
	//set share memory;
	//创建一个共享内存对象
	shmid=shmget((key_t)8891,sizeof(struct sys_data),0666|IPC_CREAT);
	if(shmid==-1)
	{
		printf("shmget error\n");
		exit(-1);
	}else{
		printf("client shmid=%d\n", shmid);
	}
	//挂载共享内存到进程中
	shm=shmat(shmid,(void*)0,0);
	if(shm==(void*)(-1))
	{
		printf("shmat error\n");
		exit(-1);
	}
	da=shm;
	while(1)
	{
		sleep(2);
		printf("temp=%.1f,humi=%.1f\n",da->data_t,
		da->data_rh );
	}

	return 0;
}

你可能感兴趣的:(linux_c,c/c++)