LinuxÄÚºËÀïÌṩµÄ/dev/memÇý¶¯£¬ÎªÎÒÃǶÁдÄÚ´æÎïÀíµØÖ·£¬ÌṩÁËÒ»¸öÇþµÀ¡£ÏÂÃæ½²Êö2ÖÖÀûÓÃmemÉ豸Îļþ½øÐÐÎïÀíµØÖ·¶ÁдµÄ·½·¨£¬Ò»ÖÖÊÇÉ豸Çý¶¯µÄ·½·¨£¬ÁíÒ»ÖÖÊÇϵͳµ÷Óõķ½·¨¡£
Ê×ÏÈÎÒÃÇ¿´ÏÂmemÕâ¸öÉ豸Îļþ£¬/dev/memÊÇlinuxϵÄÒ»¸ö×Ö·ûÉ豸£¬Ô´ÎļþÊÇ~/drivers/char/mem.c£¬Õâ¸öÉ豸ÎļþÊÇרÃÅÓÃÀ´¶ÁдÎïÀíµØÖ·Óõġ£ÀïÃæµÄÄÚÈÝÊÇËùÓÐÎïÀíÄÚ´æµÄµØÖ·ÒÔ¼°ÄÚÈÝÐÅÏ¢¡£Í¨³£Ö»ÓÐrootÓû§¶ÔÆäÓжÁдȨÏÞ¡£
1.É豸Çý¶¯µÄ·½·¨
ÏÂÃæÊÇmem.cÎļþÀﶨÒåµÄfile_operations½á¹¹£¬ÌṩÁËllseek£¬read£¬write£¬mmapÒÔ¼°openµÈ·½·¨¡£
static struct file_operations mem_fops =
{
.llseek = memory_lseek,
.read = read_mem,
.write = write_mem,
.mmap = mmap_mem,
.open = open_mem,
};
Òò´ËÎÒÃÇ¿ÉÒÔͨ¹ýÒ»°ãÇý¶¯µÄʹÓ÷½·¨£¬½«ÄÚ´æÍêÈ«µ±×÷Ò»¸öÉ豸À´¶Ô¶Ô´ý¡£Ó¦ÓóÌÐòÈçÏ£º
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *rdbuf;
char *wrbuf = "butterfly";
int i;
fd = open("/dev/mem",O_RDWR);
if(fd < 0)
{
printf("open /dev/mem failed.");
}
read(fd,rdbuf,10);
for(i = 0;i < 10;i++)
{
printf("old mem[%d]:%c\n",i,*(rdbuf + i));
}
lseek(fd,5,0);
write(fd,wrbuf,10);
lseek(fd,0,0);//move f_ops to the front
read(fd,rdbuf,10);
for(i = 0;i < 10;i++)
{
printf("new mem[%d]:%c\n",i,*(rdbuf + i));
}
return 0;
}
Ö´Ðнá¹ûÈçÏ£º½«ÄÚ´æ×ʼ10¸ö×Ö½ÚµÄÄÚÈݽøÐÐÌæ»»¡£
[root@VOIP-IPCAM app]# ./memtest
old mem[0]:b
old mem[1]:u
old mem[2]:t
old mem[3]:t
old mem[4]:e
old mem[5]:r
old mem[6]:f
old mem[7]:l
old mem[8]:y
old mem[9]:!
new mem[0]:b
new mem[1]:u
new mem[2]:t
new mem[3]:t
new mem[4]:e
new mem[5]:b
new mem[6]:u
new mem[7]:t
new mem[8]:t
new mem[9]:e
ÔÎÄ: http://hi.baidu.com/liuming910/blog/item/b2b19f59ff296888800a18b7.html