SHMOP

Section: Linux Programmer's Manual (2)
Updated: 2020-04-11
Index JM Home Page
 

名前

shmat, shmdt - System V 共有メモリー (shared memory) の操作  

書式

#include <sys/types.h>
#include <sys/shm.h>

void *shmat(int shmid, const void *shmaddr, int shmflg);

int shmdt(const void *shmaddr);
 

説明

 

shmat()

shmat() は shmid で指定された System V 共有メモリーセグメント (shared memory segment) を コールしたプロセスのアドレス空間に付加 (attach) する。 付加するアドレスは shmaddr に以下のどれかの形式で指定する:
shmaddr が NULL ならば、システムはセグメントを付加するための 適切な (使用されていない) ページ境界のアドレスを選択する。
shmaddr が NULL でなく SHM_RNDshmflg に指定されている場合は、 shmaddrSHMLBA の倍数へと切り捨てた (rounding down) のと等しいアドレスへ付加する。
その他の場合は shmaddr は付加を行なうアドレスで、ページ境界を指している必要がある。

SHM_RND に加えて、以下のフラグを shmflg ビットマスク引数に指定できる。

SHM_EXEC (Linux 固有; Linux 2.6.9 以降)
セグメントの内容を実行できる。 呼び出し元はセグメントに対する実行許可を持っていなければならない。
SHM_RDONLY
セグメントを読み込み専用に付加する。 プロセスはそのセグメントへの読み込み許可を持っていなければならない。 このフラグが指定されなかった場合、そのセグメントは読み込みと書き込みアクセスのために付加され、 プロセスはそのセグメントに読み込みと書き込みの許可を持っていなければならない。 書き込み専用の共有メモリーセグメントという概念は存在しない。
SHM_REMAP (Linux 固有)
このフラグは、 セグメントのマッピングを既存のマッピングに置き換えることを指示する。 マッピングの範囲は、 shmaddr から始まりセグメントのサイズ分だけある (通常 EINVAL エラーは、このアドレス範囲にマッピングが既に存在するために起る)。 このフラグを指定する場合は、 shmaddr が NULL であってはならない。

呼び出したプロセスの brk(2) の値は付加によって変化しない。 そのセグメントはプロセスが終了 (exit) したら自動的に分離 (detach) される。 同じセグメントをプロセスのアドレス空間に、読み込み専用および読み書き両用 として付加でき、また複数回付加することもできる。

成功した shmat() コールは共有メモリーセグメントに関連する shmid_ds 構造体 (shmctl(2) を参照) のメンバーを以下のように更新する:

shm_atime には現在の時刻を設定する。
shm_lpid には呼び出したプロセスのプロセス ID が設定される。
shm_nattch を 1 増加させる。
 

shmdt()

shmdt() は呼び出したプロセスのアドレス空間から shmaddr で指定されたアドレスに配置された共有メモリーセグメントを分離 (detach) する。 分離する共有メモリーセグメントは、現在 shmaddr に付加されているものでなければならない。 shmaddr は、それを付加した時に shmat() が返した値に等しくなければならない。

成功した shmdt() コールはその共有メモリーセグメントに関連する shmid_ds 構造体のメンバーを以下のように更新する:

shm_dtime には現在の時刻が設定される。
shm_lpid には呼び出したプロセスのプロセス ID が設定される。
shm_nattch を 1 減少させる。 もし 0 になり、削除マークがあった場合は そのセグメントは削除される。
 

返り値

shmat() は、成功した場合、 付加された共有メモリーセグメントのアドレスを返す。 エラーの場合、 (void *) -1 を返し、 errno にエラーの原因を示す値を設定する。

shmdt() は、成功すると 0 を返す。 エラーの場合、-1 を返し、 errno にエラーの原因を示す値を設定する。  

エラー

shmat() が失敗した場合、 errno に以下の値のどれかを設定して返す:
EACCES
The calling process does not have the required permissions for the requested attach type, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.
EIDRM
shmid が削除 (remove) された識別子 (identifier) を指している。
EINVAL
shmid の値が不正である。 shmaddr の値が境界違反 (unaligned) (つまり、ページ境界に合っておらず、 SHM_RND が指定されていない) または が不正である。 shmaddr へのセグメントの付加に失敗した。 または SHM_REMAP が指定されているが、 shmaddr が NULL であった。
ENOMEM
ディスクリプター (descriptor) やページテーブルのためのメモリーを 割り当てることができない。

shmdt() が失敗した場合、 EINVAL は以下のようにセットされる:

EINVAL
shmaddr に付加された共有メモリーセグメントが存在しない。 もしくは、 shmaddr がページ境界に合っていない。
 

準拠

POSIX.1-2001, POSIX.1-2008, SVr4.

SVID 3 で (たぶんそれより前だと思うが) shmaddr 引数の型は char * から const void * に、shmat() の返り値の型は char * から void * に変更された。  

注意

fork(2) した後、子プロセスは付加された共有メモリーセグメントを継承する。

exec(2) した後、全ての付加された共有メモリーセグメントはプロセスから分離される。

exit(2) において、全ての付加された共有メモリーセグメントはプロセスから分離される。

共有メモリーセグメントを付加する場合の移植性の高い方法としては、 shmaddr を NULL にして shmat() を使用するのがよい。 このような方法で付加される共有メモリーセグメントは、 プロセスが異なれば別のアドレスに付加される、という点に注意すること。 よって共有メモリー内で管理されるポインターは、 絶対アドレスではなく、 (一般的にはセグメントの開始アドレスからの) 相対アドレスで作成するべきである。

Linux では共有メモリーセグメントに既に削除マークが付けられていても、 その共有メモリーセグメントを付加することができる。 しかし POSIX.1 ではこのような動作を指定しておらず、 他の多くの実装もこれをサポートしていない。

以下のシステムパラメーターは、 shmat() に影響する:

SHMLBA
セグメントの下限アドレス倍数 (Segment low boundary address multiple)。 shmat() の呼び出しにおいて付加するアドレスを明示的に指定する際、 呼び出し元は指定するアドレスがこの値の倍数になるように保証しなければならない。 これはいくつかのアーキテクチャーでは必要なことで、 CPU キャッシュの性能を保証するためであったり、 同じセグメントの別の付与を CPU キャッシュ内部で一貫して扱えるようにするためだったりする。 SHMLBA は通常はシステムページサイズの倍数である (Linux の多くのアーキテクチャーでは SHMLBA はシステムページサイズと同じである)。

現在の実装では、プロセスごとの 共有メモリーセグメントの最大数 (SHMSEG) に関する実装依存の制限はない。  

The two programs shown below exchange a string using a shared memory segment. Further details about the programs are given below. First, we show a shell session demonstrating their use.

In one terminal window, we run the "reader" program, which creates a System V shared memory segment and a System V semaphore set. The program prints out the IDs of the created objects, and then waits for the semaphore to change value.

$ ./svshm_string_read shmid = 1114194; semid = 15

In another terminal window, we run the "writer" program. The "writer" program takes three command-line arguments: the IDs of the shared memory segment and semaphore set created by the "reader", and a string. It attaches the existing shared memory segment, copies the string to the shared memory, and modifies the semaphore value.

$ ./svshm_string_write 1114194 15 'Hello, world'

Returning to the terminal where the "reader" is running, we see that the program has ceased waiting on the semaphore and has printed the string that was copied into the shared memory segment by the writer:

Hello, world  

プログラムのソース: svshm_string.h

The following header file is included by the "reader" and "writer" programs.

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

#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
                        } while (0)

union semun { /* Used in calls to semctl() */
    int                 val;
    struct semid_ds *   buf;
    unsigned short *    array; #if defined(__linux__)
    struct seminfo *    __buf; #endif };

#define MEM_SIZE 4096  

プログラムのソース: svshm_string_read.c

The "reader" program creates a shared memory segment and a semaphore set containing one semaphore. It then attaches the shared memory object into its address space and initializes the semaphore value to 1. Finally, the program waits for the semaphore value to become 0, and afterwards prints the string that has been copied into the shared memory segment by the "writer".

/* svshm_string_read.c


   Licensed under GNU General Public License v2 or later. */ #include "svshm_string.h"

int main(int argc, char *argv[]) {
    int semid, shmid;
    union semun arg, dummy;
    struct sembuf sop;
    char *addr;


    /* Create shared memory and semaphore set containing one
       semaphore */


    shmid = shmget(IPC_PRIVATE, MEM_SIZE, IPC_CREAT | 0600);
    if (shmid == -1)
        errExit("shmget");


    semid = semget(IPC_PRIVATE, 1, IPC_CREAT | 0600);
    if (shmid == -1)
        errExit("shmget");


    /* Attach shared memory into our address space */


    addr = shmat(shmid, NULL, SHM_RDONLY);
    if (addr == (void *) -1)
        errExit("shmat");


    /* Initialize semaphore 0 in set with value 1 */


    arg.val = 1;
    if (semctl(semid, 0, SETVAL, arg) == -1)
        errExit("semctl");


    printf("shmid = %d; semid = %d\n", shmid, semid);


    /* Wait for semaphore value to become 0 */


    sop.sem_num = 0;
    sop.sem_op = 0;
    sop.sem_flg = 0;


    if (semop(semid, &sop, 1) == -1)
        errExit("semop");


    /* Print the string from shared memory */


    printf("%s\n", addr);


    /* Remove shared memory and semaphore set */


    if (shmctl(shmid, IPC_RMID, NULL) == -1)
        errExit("shmctl");
    if (semctl(semid, 0, IPC_RMID, dummy) == -1)
        errExit("semctl");


    exit(EXIT_SUCCESS); }  

プログラムのソース: svshm_string_write.c

The writer program takes three command-line arguments: the IDs of the shared memory segment and semaphore set that have already been created by the "reader", and a string. It attaches the shared memory segment into its address space, and then decrements the semaphore value to 0 in order to inform the "reader" that it can now examine the contents of the shared memory.

/* svshm_string_write.c


   Licensed under GNU General Public License v2 or later. */ #include "svshm_string.h"

int main(int argc, char *argv[]) {
    int semid, shmid;
    struct sembuf sop;
    char *addr;
    size_t len;


    if (argc != 4) {
        fprintf(stderr, "Usage: %s shmid semid string\n", argv[0]);
        exit(EXIT_FAILURE);
    }


    len = strlen(argv[3]) + 1;  /* +1 to include trailing '\0' */
    if (len > MEM_SIZE) {
        fprintf(stderr, "String is too big!\n");
        exit(EXIT_FAILURE);
    }


    /* Get object IDs from command-line */


    shmid = atoi(argv[1]);
    semid = atoi(argv[2]);


    /* Attach shared memory into our address space and copy string
       (including trailing null byte) into memory. */


    addr = shmat(shmid, NULL, 0);
    if (addr == (void *) -1)
        errExit("shmat");


    memcpy(addr, argv[3], len);


    /* Decrement semaphore to 0 */


    sop.sem_num = 0;
    sop.sem_op = -1;
    sop.sem_flg = 0;


    if (semop(semid, &sop, 1) == -1)
        errExit("semop");


    exit(EXIT_SUCCESS); }  

関連項目

brk(2), mmap(2), shmctl(2), shmget(2), capabilities(7), shm_overview(7), sysvipc(7)  

この文書について

この man ページは Linux man-pages プロジェクトのリリース 5.10 の一部である。プロジェクトの説明とバグ報告に関する情報は https://www.kernel.org/doc/man-pages/ に書かれている。

関連キーワード

セグメント, 付加, string, memory, shared, shmid, shmaddr, メモリー, 共有, shmat

Linux マニュアル 一覧

[man1] [man2] [man3] [man4] [man5] [man6] [man7] [man8]
[a] [b] [c] [d] [e] [f] [g] [h] [i] [j] [k] [l] [m] [n] [o] [p] [q] [r] [s] [t] [u] [v] [w] [x] [y] [z]

 

Index

名前
書式
説明
shmat()
shmdt()
返り値
エラー
準拠
注意
プログラムのソース: svshm_string.h
プログラムのソース: svshm_string_read.c
プログラムのソース: svshm_string_write.c
関連項目
この文書について

This document was created by man2html, using the manual pages.
Time: 12:08:47 GMT, June 11, 2022