System V IPC (訊息佇列、共享記憶體、信號燈) 需透過 key_t 識別資源,ftok() 是將路徑名與專案 ID 轉換為 key_t 的標準函式。
#include
key_t ftok(const char *pathname, int proj_id);
// 運算邏輯 (Linux 實作)
key_t = (proj_id & 0xFF) << 24 | (st_ino & 0xFFFF) << 8 | (st_dev & 0xFF)
// st_ino: inode 號, st_dev: 設備號
// 僅使用 proj_id 低 8 bits (0-255)
pathname 必須存在且可存取 (通常用 /tmp 或專用檔案)proj_id 只取低 8 位元 (0-255),超出會截斷
ls -i /tmp/my_ipc_file
stat /tmp/my_ipc_file
#include
#include
#include
#include
#include
#include
#include
#define SHM_SIZE 4096
#define PROJ_ID 0x42 // 任意 0-255
#define PATHNAME "/tmp/ipc_keyfile"
int main() {
// 1. 確保路徑存在
FILE *fp = fopen(PATHNAME, "a");
if (!fp) { perror("fopen"); exit(1); }
fclose(fp);
// 2. 產生 key
key_t key = ftok(PATHNAME, PROJ_ID);
if (key == -1) { perror("ftok"); exit(1); }
printf("Generated key: 0x%x\n", key);
// 3. 建立/取得共享記憶體段
int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0640);
if (shmid == -1) { perror("shmget"); exit(1); }
printf("shmid: %d\n", shmid);
// 4. 連接至位址空間
void *shm_addr = shmat(shmid, NULL, 0);
if (shm_addr == (void *)-1) { perror("shmat"); exit(1); }
// 5. 讀寫測試
sprintf((char *)shm_addr, "Hello from PID %d", getpid());
printf("Written: %s\n", (char *)shm_addr);
// 6. 脫離
shmdt(shm_addr);
// 7. 刪除 (標記刪除,最後脫離時生效)
// shmctl(shmid, IPC_RMID, NULL);
return 0;
}
gcc -o shm_demo shm_demo.c
./shm_demo
# 另開終端執行相同程式,應讀到相同內容
ipcs -m # 查看共享記憶體段
int shmid = shmget(IPC_PRIVATE, SHM_SIZE, 0600);
// 忽略 key,核心保證唯一,適合父子進程私有共享 (fork 後繼承 shmid)
0640 = 擁有者讀寫、群組讀、其他無shmctl(shmid, IPC_STAT, &buf) 檢查 shm_perm
# 查看目前限制
ipcs -l
cat /proc/sys/kernel/shmmax # 單段最大位元組 (預設 18446744073692774399 實際受記憶體限制)
cat /proc/sys/kernel/shmall # 總頁數
cat /proc/sys/kernel/shmmni # 最大段數 (預設 4096)
# 修改 (永久寫入 /etc/sysctl.d/99-shm.conf)
kernel.shmmax = 17179869184 # 16GB
kernel.shmall = 4194304 # 16GB / 4KB
kernel.shmmni = 8192
sysctl --system
IPC_PRIVATE + 檔案傳遞 shmid (Unix Domain Socket 傳遞 fd)/var/run/myapp/ 放置 keyfile,確保 inode 穩定ftok() 雖屬舊式 API,但在 System V IPC 必須使用的場景 (舊代碼維護、特定 Unix 相容) 仍為標準鍵值生成方式;新專案優先考慮 POSIX shm_open + mmap 機制。