首页 > 代码库 > linux:共享内存

linux:共享内存

#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:共享内存