我的一个项目有点问题。
我一直在尝试找到一个使用 fork()
的共享内存的有据可查的示例,但没有成功。
基本上场景是当用户启动程序时,我需要在共享内存中存储两个值:current_path 是一个 char* 和一个 file_name 也是 char*。
根据命令参数,使用 fork()
启动一个新进程,该进程需要读取和修改存储在共享内存中的 current_path 变量,而file_name 变量是只读的。
有没有关于共享内存的很好的教程和示例代码(如果可能),你可以指导我吗?
最佳答案
有两种方法:shmget
和 mmap
。我将讨论 mmap
,因为它更现代、更灵活,但如果您更愿意使用旧的,可以查看 man shmget
(or this tutorial) - 风格的工具。
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);
}
下面是一个使用上面定义的函数来分配缓冲区的示例程序。父进程会写一条消息,fork,然后等待其子进程修改缓冲区。两个进程都可以读写共享内存。
#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: %s\n", shmem);
memcpy(shmem, child_message, sizeof(child_message));
printf("Child wrote: %s\n", shmem);
} else {
printf("Parent read: %s\n", shmem);
sleep(1);
printf("After 1s, parent read: %s\n", shmem);
}
}
https://stackoverflow.com/questions/5656530/