SHM_OPEN(3) | Linux Programmer's Manual | SHM_OPEN(3) |
shm_open, shm_unlink - POSIX 共有メモリーオブジェクトの作成/オープン/削除を行う
#include <sys/mman.h>
#include <sys/stat.h> /* mode 定数用 */
#include <fcntl.h> /* O_*
定数の定義用 */
int shm_open(const char *name, int oflag, mode_t mode);
int shm_unlink(const char *name);
-lrt でリンクする。
shm_open() は、POSIX 共有メモリーオブジェクトを新規に作成/オープンしたり、 すでに存在するオブジェクトをオープンしたりする。 POSIX 共有メモリーオブジェクトは、実際には、関係のないプロセスが 共有メモリーの同じ領域を mmap(2) するために使用することができる手段である。 shm_unlink() は、逆の操作、つまり以前に shm_open() で作成されたオブジェクトの削除を行う。
shm_open() の動作は open(2) とよく似ている。 name で作成したりオープンしたりする共有メモリーオブジェクトを指定する。 移植性を持たせるためには、共有メモリーオブジェクトは /somename という形式の名前で識別し、 その名前は、最大で NAME_MAX (すなわち 255) 文字のヌル終端された文字列で、 スラッシュで始まり、スラッシュ以外の文字が 1 文字以上続く形式 にすべきである。
oflag はビットマスクで、 O_RDONLY と O_RDWR のいずれか一方と、以下に述べる他のフラグの論理和をとったもの を指定する。
これらのフラグ値の定義は <fcntl.h> のインクルードにより得られる。
成功して完了した場合、 shm_open() は共有メモリーオブジェクトを参照する新しいファイルディスクリプターを返す。 このファイルディスクリプターは、そのプロセス内で過去にオープンされていない ファイルディスクリプターの中で最も小さな数になることが保証される。 FD_CLOEXEC フラグ (fcntl(2) を参照) が、このファイルディスクリプターに設定される。
通常、これらのファイルディスクリプターは、この後続けて実行される ftruncate(2) (新規に作成されたオブジェクトの場合のみ) と mmap(2) の呼び出しに使用される。 mmap(2) を呼び出した後は、ファイルディスクリプターをクローズしてもよく、 クローズしてもメモリーマッピングに影響を与えることはない。
shm_unlink() の動作は unlink(2) とよく似ている: 共有メモリーオブジェクト名を削除し、すべてのプロセスが処理対象の オブジェクトをアンマップした時点でオブジェクトの割り当てを解除し、 対応するメモリー領域の内容を破棄する。 shm_unlink() が成功した後で、同じ name を持つオブジェクトに対して shm_open() を行うと、 (O_CREAT が指定されていない場合) 失敗する。 (O_CREAT が指定されている場合、新しく別のオブジェクトが作成される)。
成功した場合、 shm_open() はファイルディスクリプター (非負の整数) を返す。 失敗した場合、 shm_open() は -1 を返す。 shm_unlink() は、成功した場合 0 を、エラーが起こった場合 -1 を返す。
失敗した場合、エラーの原因を示すため errno が設定される。 errno に設定される値は以下の通りである:
これらの関数は glibc 2.2 以降で提供されている。
この節で使用されている用語の説明については、 attributes(7) を参照。
インターフェース | 属性 | 値 |
shm_open(), shm_unlink() | Thread safety | MT-Safe locale |
POSIX.1-2001, POSIX.1-2008.
POSIX.1-2001 says that the group ownership of a newly created shared memory object is set to either the calling process's effective group ID or "a system default group ID". POSIX.1-2008 says that the group ownership may be set to either the calling process's effective group ID or, if the object is visible in the filesystem, the group ID of the parent directory.
POSIX は O_RDONLY と O_TRUNC が一緒に指定された場合の動作を未定義にしている。Linux では、 既存の共有メモリーオブジェクトに対する切り詰め (truncate) は成功する。 しかし、他の UNIX システムでも同じであるとは限らない。
Linux における POSIX 共有メモリーオブジェクトの実装は専用の tmpfs(5) ファイルシステムを使用する。そのファイルシステムは通常 /dev/shm にマウントされる。
The programs below employ POSIX shared memory and POSIX unnamed semaphores to exchange a piece of data. The "bounce" program (which must be run first) raises the case of a string that is placed into the shared memory by the "send" program. Once the data has been modified, the "send" program then prints the contents of the modified shared memory. An example execution of the two programs is the following:
$ ./pshm_ucase_bounce /myshm & [1] 270171 $ ./pshm_ucase_send /myshm hello HELLO
Further detail about these programs is provided below.
The following header file is included by both programs below. Its primary purpose is to define a structure that will be imposed on the memory object that is shared between the two programs.
#include <sys/mman.h> #include <fcntl.h> #include <semaphore.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \ } while (0) #define BUF_SIZE 1024 /* Maximum size for exchanged string */ /* Define a structure that will be imposed on the shared memory object */ struct shmbuf { sem_t sem1; /* POSIX unnamed semaphore */ sem_t sem2; /* POSIX unnamed semaphore */ size_t cnt; /* Number of bytes used in 'buf' */ char buf[BUF_SIZE]; /* Data being transferred */ };
The "bounce" program creates a new shared memory object with the name given in its command-line argument and sizes the object to match the size of the shmbuf structure defined in the header file. It then maps the object into the process's address space, and initializes two POSIX semaphores inside the object to 0.
After the "send" program has posted the first of the semaphores, the "bounce" program upper cases the data that has been placed in the memory by the "send" program and then posts the second semaphore to tell the "send" program that it may now access the shared memory.
/* pshm_ucase_bounce.c Licensed under GNU General Public License v2 or later. */ #include <ctype.h> #include "pshm_ucase.h" int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s /shm-path\n", argv[0]); exit(EXIT_FAILURE); } char *shmpath = argv[1]; /* Create shared memory object and set its size to the size of our structure */ int fd = shm_open(shmpath, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) errExit("shm_open"); if (ftruncate(fd, sizeof(struct shmbuf)) == -1) errExit("ftruncate"); /* Map the object into the caller's address space */ struct shmbuf *shmp = mmap(NULL, sizeof(*shmp), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (shmp == MAP_FAILED) errExit("mmap"); /* Initialize semaphores as process-shared, with value 0 */ if (sem_init(&shmp->sem1, 1, 0) == -1) errExit("sem_init-sem1"); if (sem_init(&shmp->sem2, 1, 0) == -1) errExit("sem_init-sem2"); /* Wait for 'sem1' to be posted by peer before touching shared memory */ if (sem_wait(&shmp->sem1) == -1) errExit("sem_wait"); /* Convert data in shared memory into upper case */ for (int j = 0; j < shmp->cnt; j++) shmp->buf[j] = toupper((unsigned char) shmp->buf[j]); /* Post 'sem2' to tell the to tell peer that it can now access the modified data in shared memory */ if (sem_post(&shmp->sem2) == -1) errExit("sem_post"); /* Unlink the shared memory object. Even if the peer process is still using the object, this is okay. The object will be removed only after all open references are closed. */ shm_unlink(shmpath); exit(EXIT_SUCCESS); }
The "send" program takes two command-line arguments: the pathname of a shared memory object previously created by the "bounce" program and a string that is to be copied into that object.
The program opens the shared memory object and maps the object into its address space. It then copies the data specified in its second argument into the shared memory, and posts the first semaphore, which tells the "bounce" program that it can now access that data. After the "bounce" program posts the second semaphore, the "send" program prints the contents of the shared memory on standard output.
/* pshm_ucase_send.c Licensed under GNU General Public License v2 or later. */ #include <string.h> #include "pshm_ucase.h" int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s /shm-path string\n", argv[0]); exit(EXIT_FAILURE); } char *shmpath = argv[1]; char *string = argv[2]; size_t len = strlen(string); if (len > BUF_SIZE) { fprintf(stderr, "String is too long\n"); exit(EXIT_FAILURE); } /* Open the existing shared memory object and map it into the caller's address space */ int fd = shm_open(shmpath, O_RDWR, 0); if (fd == -1) errExit("shm_open"); struct shmbuf *shmp = mmap(NULL, sizeof(*shmp), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (shmp == MAP_FAILED) errExit("mmap"); /* Copy data into the shared memory object */ shmp->cnt = len; memcpy(&shmp->buf, string, len); /* Tell peer that it can now access shared memory */ if (sem_post(&shmp->sem1) == -1) errExit("sem_post"); /* Wait until peer says that it has finished accessing the shared memory */ if (sem_wait(&shmp->sem2) == -1) errExit("sem_wait"); /* Write modified data in shared memory to standard output */ write(STDOUT_FILENO, &shmp->buf, len); write(STDOUT_FILENO, "\n", 1); exit(EXIT_SUCCESS); }
close(2), fchmod(2), fchown(2), fcntl(2), fstat(2), ftruncate(2), memfd_create(2), mmap(2), open(2), umask(2), shm_overview(7)
この man ページは Linux man-pages プロジェクトのリリース 5.10 の一部である。プロジェクトの説明とバグ報告に関する情報は https://www.kernel.org/doc/man-pages/ に書かれている。
2020-11-01 | Linux |