System V 共有メモリ

仕事で使っているPostgreSQLでは、どうやらshmgetしているみたいなので、久しぶりにサンプル書きつつLinuxでの挙動を見てみた。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>

const int shm_size = 256 * 1024 * 1024;

int main(void)
{
    int shm_id;
    void *shm_pt;

    printf("calling shmget... >\n"); getchar();

    if ((shm_id = shmget(IPC_PRIVATE, shm_size, 0666 | IPC_CREAT)) == -1) {
        perror("shmget");
        exit(EXIT_FAILURE);
    }
    printf("shm_id => %d\n", shm_id);

    printf("calling shmat... >\n"); getchar();

    if ((shm_pt = shmat(shm_id, NULL, 0)) == (void*)-1) {
        perror("shmat");
        exit(EXIT_FAILURE);
    }

    printf("calling memset... >\n"); getchar();

    memset(shm_pt, 0xFF, shm_size);

    printf("closing... >\n"); getchar();

    exit(EXIT_SUCCESS);
}

で実行〜終了〜共有メモリ削除の間、/proc/meminfoを見ていくと…

  • shmgetの直前〜memsetの直前
    • MemFree: 207552 kB
    • Cached: 395324 kB
    • Active: 302892 kB
    • Inactive: 391488 kB
  • exitの直前(memset後)〜 exit後
    • MemFree: 23996 kB
    • Cached: 585396 kB
    • Active: 434644 kB
    • Inactive: 444240 kB
  • ipcrm後
    • MemFree: 286196 kB
    • Cached: 323328 kB
    • Active: 175488 kB
    • Inactive: 441644 kB

となった。

shmgetした時点では特にメモリの状態は変化しないけれど、確保した共有メモリに書き込んでいくとページキャッシュとしてメモリが確保されているみたい。プロセスが終了してもページキャッシュは減らないのだけど、ipcrm -mすると一気に開放された。

なんとなく、裏でmmapみたいなのを呼んでいるかもしれないなぁ。