共享記憶體是被多個行程共用的同一塊實體記憶體,也是行程間交換資料最快的方式——因為資料不必在核心與使用者空間之間來回搬運。代價是它本身沒有同步機制,必須搭配訊號或訊號量使用。
需要的標頭:
#include <sys/types.h> #include <sys/shm.h>
int shmget(key_t key, int size, int shmflg);
key 由 ftok 取得;size 是大小;shmflg 是旗標(如 IPC_CREAT 搭配權限位)。成功回傳共享記憶體標識符,失敗回 -1。
int shmat(int shmid, char *shmaddr, int flag);
shmid 是 shmget 的傳回值;shmaddr 通常給 NULL 讓核心選位址。成功回傳映射後的位址,失敗回 -1。
int shmdt(char *shmaddr);
注意它只是「解除映射」,共享記憶體本身仍然存在。
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
cmd 給 IPC_RMID 才是真正的刪除。
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#define BUFFER_SIZE 128
void myfun()
{
return;
}
int main()
{
struct mybuf
{
int pid;
char buf[BUFFER_SIZE];
};
int key, shmid;
int pid;
struct mybuf *p;
signal(SIGUSR2, myfun);
key = ftok("./e.c", 'a');
if(key < 0)
{
printf("creat two process error\n");
exit(1);
}
shmid = shmget(key, BUFFER_SIZE, IPC_CREAT|S_IRWXU);
if(shmid < 0)
{
perror("shmget");
exit(1);
}
printf("create share memory success\n");
p = (struct mybuf *)shmat(shmid, NULL, 0);
if(p == NULL)
{
perror("shmat");
exit(1);
}
printf("map the share memory success\n");
p->pid = getpid(); /* 把自己的 PID 寫進共享記憶體 */
pause(); /* 等待客戶端 */
pid = p->pid; /* 讀取客戶端 PID */
while(1)
{
printf("parent process start write share memory\n");
fgets(p->buf, 124, stdin);
kill(pid, SIGUSR1);
pause();
}
shmdt(p);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#define BUFFER_SIZE 128
void my_fun()
{
return;
}
int main()
{
struct my_buf
{
int pid;
char buf[BUFFER_SIZE];
};
int key, shmid;
int pid;
struct my_buf *p;
signal(SIGUSR1, my_fun);
key = ftok("./e.c", 'a');
if(key < 0)
{
perror("ftok");
exit(1);
}
shmid = shmget(key, BUFFER_SIZE, IPC_CREAT|S_IRWXU);
if(shmid < 0)
{
perror("shmget");
exit(1);
}
p = (struct my_buf *)shmat(shmid, NULL, 0);
if(p == NULL)
{
perror("shmat");
exit(1);
}
printf("map the share memory success\n");
pid = p->pid; /* 讀取伺服器 PID */
p->pid = getpid(); /* 寫入自己的 PID */
kill(pid, SIGUSR2); /* 通知伺服器 */
while(1)
{
pause();
printf("client process recave data form share memory:%s\n", p->buf);
kill(pid, SIGUSR2);
}
shmdt(p);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
兩邊用同一組 ftok 參數(./e.c 與 'a')產生相同 key,因此連到同一塊共享記憶體。結構中刻意放了 pid 欄位,讓雙方能互相取得對方 PID 以發送訊號;訊號在這裡的角色是「通知」,真正的資料傳遞則完全靠共享記憶體,這正是兩者搭配的經典模式。
三個實務要注意的地方:一是 ftok 的路徑檔必須存在,否則回 -1;二是共享記憶體隨核心存活,只有其中一個行程呼叫 IPC_RMID 是不夠的(要等所有映射都解除才真正釋放),因此建議以 ipcs -m 定期檢查殘留;三是共享記憶體沒有內建同步,若兩個行程同時寫入會產生資料競爭,正式環境請搭配訊號量(sem)或行程間的握手協議。