Welcome to our deep dive into C Memory-Mapped I/O! This lesson is designed to teach you about an efficient method for accessing and manipulating I/O devices, like files and hardware, directly in your C programs. Let's embark on this exciting journey together! šÆ
Memory-Mapped I/O is a programming technique that enables the system to map the I/O devices' memory addresses into the process's address space, making it appear as if the device is just another memory region. This approach offers several benefits, such as:
To perform Memory-Mapped I/O in C, we'll use the mmap() function, which maps a file or a shared memory region into the process's address space.
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int fd = open("example.txt", O_RDWR | O_CREAT, 0644);
void *mapped_memory = mmap(NULL, sizeof(example), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
// Perform operations on mapped_memory
munmap(mapped_memory, sizeof(example));
close(fd);š Note:
O_RDWR: Opens the file for reading and writing.O_CREAT: Creates the file if it does not exist.0644: Sets the file permissions to read and write for the owner and read for others.PROT_READ | PROT_WRITE: Sets the mapping's protection to read and write.MAP_SHARED: Maps the file with shared memory, allowing multiple processes to access the same memory region.Now that you've learned how to map a file, let's dive into accessing and manipulating I/O devices. Here's an example of reading and writing to a file using Memory-Mapped I/O:
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
struct example {
int id;
char name[20];
};
int main() {
int fd = open("example.txt", O_RDWR | O_CREAT, 0644);
struct example *mapped_example = (struct example *)mmap(NULL, sizeof(struct example), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
mapped_example->id = 1234;
strcpy(mapped_example->name, "John Doe");
munmap(mapped_example, sizeof(struct example));
close(fd);
// Print the content of example.txt
FILE *file = fopen("example.txt", "r");
struct example example;
fread(&example, sizeof(struct example), 1, file);
printf("ID: %d\nName: %s\n", example.id, example.name);
fclose(file);
return 0;
}š Note:
struct example to store the data we want to read and write, in this case, an ID and a name.mmap().fread().Now that you've learned the basics of C Memory-Mapped I/O, let's test your knowledge with a quiz!
What is Memory-Mapped I/O, and why is it useful?
We hope you've enjoyed learning about C Memory-Mapped I/O! With this newfound knowledge, you can now create more efficient and practical C programs involving I/O devices. Happy coding! š