我对我的一个项目有一点意见.
我一直在努力寻找一个使用fork()
个共享内存的好例子,但没有成功.
基本上情况是,当用户启动程序时,我需要在共享内存中存储两个值:current_path是char*,file_name也是char*.
根据命令参数,一个新进程以fork()
开始,该进程需要读取和修改存储在共享内存中的current_path变量,而file_name变量是只读的.
有没有关于共享内存的好教程(如果可能的话)可以让我参考?
我对我的一个项目有一点意见.
我一直在努力寻找一个使用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);
}
下面是一个示 routine 序,它使用上面定义的函数来分配缓冲区.父进程将编写一条消息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);
}
}