System V IPC (訊息佇列、信號量、共享記憶體) 需要一個 key_t 鍵值標識資源。ftok() 根據**既有檔案的 inode 號**與**專案 ID (8 bits)** 產生鍵值。本文解析原理、參數限制、鍵值衝突風險,並給出共享記憶體 shmget/shmat/shmctl 完整父子進程通訊範例。
#include
#include
key_t ftok(const char *pathname, int proj_id);
pathname:必須**存在且可存取**的檔案路徑 (常用 /tmp、/dev/null、專案根目錄)。proj_id:僅低 8 位元有效 (0-255),作為子序號區分同一檔案的不同 IPC 物件。key_t,失敗 -1 (設 errno)。
key_t = (proj_id & 0xFF) << 24 | (inode & 0xFFFFF) | (dev_minor & 0xFF) << 20
// 簡化說明:proj_id 佔高位,inode 佔中低位
範例:inode=65538 (0x10002)、proj_id=38 (0x26) → key=0x26010002。
ls -i /path/to/file
stat /path/to/file
key_t key = ftok("/dev/null", 1); 取得鍵值shmget(key, SIZE, 0600 | IPC_CREAT | IPC_EXCL) 建立/取得段 (返回 shmid)shmat(shmid, NULL, 0) 掛接至進程位址空間 (返回指標)memcpy, strcpy)shmdt(ptr) 卸載shmctl(shmid, IPC_RMID, NULL) 標記刪除 (最後一個進程卸載後實際釋放)
#include
#include
#include
#include
#include
#include
#include
#define SIZE 1024
int main() {
pid_t pid;
key_t key;
int shmid;
char *shmptr;
if ((pid = fork()) < 0) { perror("fork"); exit(1); }
if (pid == 0) { // Child
sleep(2);
if ((key = ftok("/dev/null", 1)) == -1) { perror("ftok"); exit(1); }
if ((shmid = shmget(key, SIZE, 0600)) == -1) { perror("shmget"); exit(1); }
if ((shmptr = shmat(shmid, NULL, 0)) == (void*)-1) { perror("shmat"); exit(1); }
printf("Child PID=%d: %s\n", getpid(), shmptr);
sleep(2);
shmdt(shmptr);
shmctl(shmid, IPC_RMID, NULL);
exit(0);
} else { // Parent
if ((key = ftok("/dev/null", 1)) == -1) { perror("ftok"); exit(1); }
if ((shmid = shmget(key, SIZE, 0600 | IPC_CREAT | IPC_EXCL)) == -1) { perror("shmget"); exit(1); }
if ((shmptr = shmat(shmid, NULL, 0)) == (void*)-1) { perror("shmat"); exit(1); }
strcpy(shmptr, "hello world");
printf("Parent PID=%d: wrote '%s'\n", getpid(), shmptr);
sleep(2);
shmdt(shmptr);
shmctl(shmid, IPC_RMID, NULL);
waitpid(pid, NULL, 0);
}
return 0;
}
Parent PID=1234: wrote 'hello world' Child PID=1235: hello world
pathname + proj_id 會產生相同 key,導致 IPC 物件誤共用。建議各專案使用獨特路徑 (如專案根目錄下專屬檔案)。IPC_PRIVATE:shmget(IPC_PRIVATE, ...) 建立私有段,不需 key,僅限父子/關聯進程使用 (需傳遞 shmid)。shm_open/mmap) 名稱空間更清晰、支援檔案權限、易於除錯,**新專案優先考慮**。