C
Shared memory
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).
Exercise 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);.
Show example 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;
}
Test yourself
-
shmget call
int shmid = shmget(IPC_PRIVATE, 64, 0600 | ____);
Show answer
int shmid = shmget(IPC_PRIVATE, 64, 0600 | IPC_CREAT);
-
Match shared memory functions
- shmget
- Creates segment
- shmat
- Attaches to process
- shmdt
- Detaches
- shmctl
- Removes segment
-
What does shmat return?
- void * pointer
- int descriptor
- long size
- pid_t id
Show answer
void * pointer — shmat returns the mapped address as void *.
Next lesson: Message queue