有两种方法:
shmget和
mmap。我将讨论
mmap,因为它更现代,更灵活,但是如果您想使用旧式工具,可以看看
manshmget(或本教程)。
该
mmap()函数可用于分配具有高度可自定义参数的内存缓冲区,以控制访问和权限,并在必要时通过文件系统存储支持它们。
以下函数创建一个进程中可以与其子进程共享的内存中缓冲区:
#include <stdio.h>#include <stdlib.h>#include <sys/mman.h>void* create_shared_memory(size_t size) { // Our memory buffer will be readable and writable: int protection = PROT_READ | PROT_WRITE; // The buffer will be shared (meaning other processes can access it), but // anonymous (meaning third-party processes cannot obtain an address for it), // so only this process and its children will be able to use it: int visibility = MAP_SHARED | MAP_ANONYMOUS; // The remaining parameters to `mmap()` are not important for this use case, // but the manpage for `mmap` explains their purpose. return mmap(NULL, size, protection, visibility, -1, 0);}下面是一个示例程序,该程序使用上面定义的功能来分配缓冲区。父进程将编写一条消息,进行分叉,然后等待其子进程修改缓冲区。这两个进程都可以读取和写入共享内存。
#include <string.h>#include <unistd.h>int main() { char parent_message[] = "hello"; // parent process will write this message char child_message[] = "goodbye"; // child process will then write this one void* shmem = create_shared_memory(128); memcpy(shmem, parent_message, sizeof(parent_message)); int pid = fork(); if (pid == 0) { printf("Child read: %sn", shmem); memcpy(shmem, child_message, sizeof(child_message)); printf("Child wrote: %sn", shmem); } else { printf("Parent read: %sn", shmem); sleep(1); printf("After 1s, parent read: %sn", shmem); }}


