系統建立 IPC 通訊(如訊息佇列、共享記憶體)時必須指定一個 ID 值,通常透過 ftok 函數取得。
原型為:key_t ftok(char *fname, int id)。fname 是必須存在且可存取的檔案名稱,id 是子序號,雖為 int 但只使用 8 個位元(0-255)。成功時回傳 key_t 值,失敗回傳 -1。
一般 UNIX 實作會取出檔案的 inode 號,前面加上子序號組成回傳值。例如 inode 為 65538(0x010002),ID 為 38(0x26),最終 key_t 即為 0x26010002。可用 ls -i 查詢 inode 號。
以下為測試程式:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#define IPCKEY 0x11
int main(void) {
int i=0;
for (i = 1; i < 256; ++i)
printf("key = %x\n", ftok("/tmp", i));
return 0;
}
取得 key 後,即可作為 shmget 等 IPC 方法的 key 值。shmget 原型為 int shmget(key_t, size_t, flag),成功後回傳共享記憶體描述符。以下為建立共享記憶體的簡例:
#include <sys/shm.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 1024
int main() {
int shmid;
char *shmptr;
if((shmid = shmget(IPC_PRIVATE, SIZE, 0600)) < 0) {
printf("shmget error:%s\n", strerror(errno));
return -1;
}
if((shmptr = (char*)shmat(shmid, 0, 0)) == (void*)-1) {
printf("shmat error:%s\n", strerror(errno));
return -1;
}
memcpy(shmptr, "hello world", sizeof("hello world"));
if((shmctl(shmid, IPC_RMID, 0) < 0)) {
printf("shmctl error:%s\n", strerror(errno));
return -1;
}
}
多行程共享記憶體的情況則可搭配 fork,父子行程各自以 ftok("/dev/null", 1) 取得相同 key,再透過 shmget 與 shmat 存取同一段共享記憶體。
作者 軌跡16