Shared memory
- C course
- Advanced
- Lesson 33/83
- 5 min
Learn shared memory with shmget and shmat.
Shared memory
Shared memory is the mapping of the same physical memory region into processes; it is the fastest IPC method because the kernel does no copying. A segment is created with shmget(key, size, flags) and attached to the process address space with shmat(shmid, NULL, 0).
The IPC_PRIVATE key always produces a new and unique segment; if created before fork, the child inherits the mapping. 0600 | IPC_CREAT is a common choice for flags. When done, shmdt detaches and shmctl(shmid, IPC_RMID, NULL) removes the segment.
shmat and fork
shmat returns a void * pointer; you cast it to the type you want. The parent obtains it with int *shared = (int *)shmat(shmid, NULL, 0); and writes with *shared = 42;. After fork the child inherits the same mapping, so reading *shared gives 42.
No synchronization is needed because the parent writes before fork; the value is ready when the child reads. If the order needs reversing, synchronize with a semaphore or flag. When done, detach with shmdt(shared) and remove with shmctl(shmid, IPC_RMID, NULL).
Practice Write a value to shared memory
Create a segment with int shmid = shmget(IPC_PRIVATE, 64, 0600 | IPC_CREAT);. Attach with int *shared = (int *)shmat(shmid, NULL, 0);. Write with *shared = 42;. Fork a child with pid_t pid = fork();. In the child: printf("%d\n", *shared);, shmdt(shared); _exit(0);. In the parent: wait(NULL);, shmdt(shared);, shmctl(shmid, IPC_RMID, NULL);.
Starter code
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
// Create shared memory segment and attach
// Fork a child to read
// Parent waits and cleans up
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int shmid = shmget(IPC_PRIVATE, 64, 0600 | IPC_CREAT);
int *shared = (int *)shmat(shmid, NULL, 0);
*shared = 42;
pid_t pid = fork();
if (pid == 0) {
printf("%d\n", *shared);
shmdt(shared);
_exit(0);
}
wait(NULL);
shmdt(shared);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 shmget call
int shmid = shmget(IPC_PRIVATE, 64, 0600 | ____);
int shmid = shmget(IPC_PRIVATE, 64, 0600 | IPC_CREAT);
Explanation: IPC_CREAT creates the segment if it does not exist.
2 Match shared memory functions
| Term | Meaning |
|---|---|
shmget |
Creates segment |
shmat |
Attaches to process |
shmdt |
Detaches |
shmctl |
Removes segment |
3 What does shmat return?
- void * pointer Correct answer
- int descriptor
- long size
- pid_t id
Explanation: shmat returns the mapped address as void *.