Shared memory คือหน่วยความจำร่วมระหว่าง 2 process หรือมากกว่า แต่ทำไมต้อง share memory หรือ IPC อื่นๆ?
แต่ละ process มี address space ของตัวเอง หาก process ใดต้องการสื่อสารข้อมูลจาก address space ของมันไปยัง process อื่น จำเป็นต้องใช้ IPC สื่อสารได้ทั้ง related และ unrelated processes
Related processes มักใช้ Pipes/Named Pipes Unrelated processes (รันคนละ terminal) ใช้ Named Pipes, Shared Memory, Message Queues
IPC techniques: Pipes, Named pipes, Shared Memory, Message Queues, Semaphores, Signals, Memory Mapping 
System calls สำหรับ shared memory:
- สร้างหรือใช้ shared memory segment (shmget())
- Attach process ไปยัง shared memory (shmat())
- Detach process จาก shared memory (shmdt())
- Control operations (shmctl())
สร้าง 2 process: หนึ่งเขียน หนึ่งอ่าน
ตัวอย่าง Writer
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main() {
key_t my_key = ftok("shmfile", 65); // ftok สร้าง unique key
int shmid = shmget(my_key, 1024, 0666 | IPC_CREAT); // shmget คืน id
char *str = (char*) shmat(shmid, (void*)0, 0); // shmat attach
cout << "Write Data: ";
fgets(str, 50, stdin);
printf("Data written in memory: %s\n", str);
shmdt(str); // detach
}
ตัวอย่าง Reader
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main() {
key_t my_key = ftok("shmfile", 65);
int shmid = shmget(my_key, 1024, 0666 | IPC_CREAT);
char *str = (char*) shmat(shmid, (void*)0, 0);
printf("Data read from memory: %s\n", str);
shmdt(str);
shmctl(shmid, IPC_RMID, NULL); // ทำลาย shared memory
}
ผลลัพธ์
