Article title: user mode and kernel shared memory: the simplest example. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
# Include
# Include
# Include
# Include
MODULE_LICENSE ("GPL ");
MODULE_AUTHOR ("Wheelz ");
MODULE_DESCRIPTION ("mmap demo ");
Static unsigned long p = 0;
Static int _ init (void)
{
// Allocate shared memory (one page)
P = _ get_free_pages (GFP_KERNEL, 0 );
SetPageReserved (pai_to_page (p ));
Printk ("<1> p = 0x % 08x \ n", p );
// Write a string in the shared memory
Strcpy (p, "Hello world! \ N ");
Return 0;
}
Static void _ exit fini (void)
{
ClearPageReserved (Fig (p ));
Free_pages (p, 0 );
}
Module_init (init );
Module_exit (fini );
User State program ---------------------------------
# Include
# Include
# Include
# Include
# Include
# Define PAGE_SIZE (4*1024)
# Define PAGE_OFFSET 0xc0000000
# Define KERNEL_VIRT_ADDR 0xc5e3c000
Int main ()
{
Char * buf;
Int fd;
Unsigned long phy_addr;
Fd = open ("/dev/mem", O_RDWR );
If (fd =-1)
Perror ("open ");
Phy_addr = KERNEL_VIRT_ADDR-PAGE_OFFSET;
Buf = mmap (0, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, phy_addr );
If (buf = MAP_FAILED)
Perror ("mmap ");
Puts (buf); // Print shared memory content
Munmap (buf, PAGE_SIZE );
Close (fd );
Return 0;
}