mmap¶
mmap() maps a file, device, or shared memory object into a process address space.
Prototype¶
#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags,
int fd, off_t offset);
Typical Shared Memory Mapping¶
void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
return -1;
}
Key Parameters¶
| Parameter | Description |
|---|---|
length |
Mapping size |
prot |
Access permission, such as PROT_READ or PROT_WRITE |
flags |
Use MAP_SHARED for shared memory IPC |
fd |
File descriptor returned by shm_open() or another file/device open |
offset |
Mapping offset, usually 0 for simple shared memory usage |
Return Value¶
- mapped address on success
MAP_FAILEDon error, witherrnoset
Common Pitfalls¶
Warning
MAP_SHARED is required when updates must be visible to other processes.
Note
mmap() does not provide synchronization. Use locks, semaphores, or another notification mechanism when multiple processes access shared data.