内存共享基本演示

发送端: 申请共享内存区域并写入数据到共享内存区域

sender.c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/shm.h>



#define BUFSIZ 102400

int main()

{

	int shmid=-1;

	char * viraddr;

	char buffer[BUFSIZ];

	key_t shmkey = ftok("/home/cip/test/", 0);

	shmid = shmget(shmkey,BUFSIZ, IPC_CREAT|0666); //申请共享区域

	viraddr=(char*)shmat(shmid,0,0); //附件共享地址到将本进程

	while(1)

	{

		puts("enter some text:");

		fgets(buffer, BUFSIZ, stdin);

		strcat(viraddr,buffer);添加数据到共享内存中

		if(strncmp(buffer,"end",3)==0)

		{

			break;

		}

	}

	shmdt(viraddr); //撤销地址映射

	

	return 0;

}


gcc -o send sender.c

 

接收端:

读取共享区的内容

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/shm.h>



#define BUFSIZ 102400

int main()

{

	int shmid=-1;

	char * viraddr;

	char buffer[BUFSIZ];

	key_t shmkey = ftok("/home/cip/test/", 0);





	shmid = shmget(shmkey,BUFSIZ, IPC_CREAT|0666); //获取共享区域

	viraddr=(char*)shmat(shmid,0,0);

	printf("Your message is:\n%s", viraddr);

	shmdt(viraddr);

	shmctl(shmid, IPC_RMID,0);

	

	return 0;

}



 

 

 

 

你可能感兴趣的:(内存)