1. 程式人生 > >記憶體共享對映的實現

記憶體共享對映的實現

//記憶體共享對映
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main(void)
{
	int fd, len;
	int *p;
	fd = open("hello", O_RDWR);//將fd與hello檔案連線
	if(fd<0)
	{
		perror("open");
		exit(1);
	}

	len = lseek(fd, 0, SEEK_END);//讀取hello檔案的大小
	p = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);//建立對映
	if(p==MAP_FAILED)
	{
		perror("mmap");
		exit(1);
	}
	close(fd);
	P[0]=0x30313233;//修改記憶體中資料
	munmap(p, len);//釋放對映記憶體,關閉對映
	return 0;
}