/*
file: mem.c
function: Read the the first 5 bytes of the memory and then Write it with "HELLO"
*/
#include
#include
#include
#include
#include
#include
int main (int args, char* arg[])
{
int i;
int fd;
char* mem;
char *buff = "HELLO";
//open /dev/mem with read and write mode
if ((fd = open ("/dev/mem", O_RDWR)) < 0)
{
perror ("open error";
return -1;
}
//map physical memory 0-10 bytes
mem = mmap (0, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mem == MAP_FAILED) {
perror ("mmap error:";
return 1;
}
//Read old value
for (i = 0; i < 5; i++)
{
printf("\nold mem[%d]:%d", i, mem[i]);
}
//write memory
memcpy(mem, buff, 5);
//Read new value
for (i = 0; i<5 ; i++)
{
printf("\nnew mem[%d]:%c", i, mem[i]);
}
printf("\n";
munmap (mem, 10); //destroy map memory
close (fd); //close file
return 0;
}
2.编译、运行:
#gcc -o mem mem.c#./mem结果如下:old mem[0]:1old mem[1]:0old mem[2]:0old mem[3]:0old mem[4]:83new mem[0]:Hnew mem[1]:Enew mem[2]:Lnew mem[3]:Lnew mem[4]:O