码迷,mamicode.com
首页 > 系统相关 > 详细

linux:共享内存

时间:2017-06-28 17:10:59      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:linux   stdio.h   共享内存   tac   pre   clu   data   shmget   data-   

#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct shared_use_st
{
	int flags;
	char buff[1000];
};
int main()
{
	void *shared_memory = NULL;
	int shmid = shmget((key_t)1234,sizeof(shared_use_st),0666|IPC_CREAT);
	if(shmid==-1)
	{
		fprintf(stderr,"shmget failed\n");
		exit(0);
	}
	
	shared_memory = shmat(shmid,(void *)0,0);
	if(shared_memory==(void *)-1)
	{
		printf("Error");
		exit(0);
	}
	printf("Memory attached at %x\n",(int)shared_memory);
	
	shared_use_st *shared_buff = (shared_use_st*)shared_memory;
	shared_buff->flags = 0;
	if(fork()==0)
	{
		while(1)
		{
		 while(shared_buff->flags==0)
		 {
			strncpy(shared_buff->buff,"liuhuiyan",10);
			shared_buff->flags = 1;
			sleep(1);
		 }
		}		
	}
	else
	{
		while(1)
		{
			while(shared_buff->flags==1)
			{
				char data_buff[100];
				strcpy(data_buff,shared_buff->buff);
				cout<<data_buff<<endl;
				shared_buff->flags=0;	
			}
		}
	}
	shmdt(shared_memory);
	return 0;
}

linux:共享内存

标签:linux   stdio.h   共享内存   tac   pre   clu   data   shmget   data-   

原文地址:http://www.cnblogs.com/yangykaifa/p/7090311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!