您的位置:首页 > 运维架构 > Linux

IPC 简单的读写通信实例 linux环境高级编程

2012-09-18 14:43 597 查看
先在当前目录即编译目录下 是有touch建立 myshm文件

然后依次编译以下两个文件

shm_write

#include <fcntl.h>
#include <stdio.h>
#include "apue.h"
#include <errno.h>
#include <sys/wait.h>
#include "sys/types.h"
#include <unistd.h>
#include <stropts.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <string.h>

typedef struct {
	char name[4];
	int age;
}people;

int main(int argc,char *argv[])
{
	int i,shmid;
	key_t key;
	char temp;
	people *p_map;
	char *name="./myshm";
	//创建一个键值
	key=ftok(name,1);
	perror("ftok");
	//获取共享内存id,也即创建ipc
	shmid=shmget(key,4096,IPC_CREAT|00666);
	perror("shmget");
	//返回共享内存的地址
	p_map=(people *)shmat(shmid,NULL,0);
	temp='a';
	for(i=0;i<10;i++)
		{
			memcpy((*(p_map+i)).name,&temp,1);
			(*(p_map+i)).age=20+i;
			
		}
}


shm_read

#include <fcntl.h>
#include <stdio.h>
#include "apue.h"
#include <errno.h>
#include <sys/wait.h>
#include "sys/types.h"
#include <unistd.h>
#include <stropts.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <string.h>
//读端程序
typedef struct {
	char name[4];
	int age;
}people;

int main(int argc,char *argv[])
{
	int i,shmid;
	key_t key;
	char temp;
	people *p_map;
	char *name="./myshm";
	//创建一个键值
	key=ftok(name,1);
	perror("ftok");
	//获取共享内存id,也即创建ipc
	shmid=shmget(key,4096,IPC_CREAT|00666);
	perror("shmget");
	//返回共享内存的地址
	p_map=(people *)shmat(shmid,NULL,0);
	temp='a';
	for(i=0;i<10;i++)
		{
			printf("name %s\n",(*(p_map+i)).name);
			printf("age %d\n",(*(p_map+i)).age);
			
		}
	//unlink
	shmdt(p_map);
	perror("shmdt");
	
}


然后先执行./shm_write

再执行 ./shm_read

就可以看到读到的数据了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐