如何在 Linux 中用 C 语言使用共享内存
我的一个项目有点问题。
我一直试图找到一个有据可查的使用 fork()
共享内存的示例,但没有成功。
基本上情况是,当用户启动程序时,我需要在共享内存中存储两个值:current_path,它是一个char*和一个file_name 也是char*。
根据命令参数,使用 fork()
启动一个新进程,该进程需要读取和修改存储在共享内存中的 current_path 变量,而 file_name 变量是只读的。
是否有关于共享内存的很好的教程以及示例代码(如果可能)可以指导我?
I have a bit of an issue with one of my projects.
I have been trying to find a well documented example of using shared memory with fork()
but to no success.
Basically the scenario is that when the user starts the program, I need to store two values in shared memory: current_path which is a char* and a file_name which is also char*.
Depending on the command arguments, a new process is kicked off with fork()
and that process needs to read and modify the current_path variable stored in shared memory while the file_name variable is read only.
Is there a good tutorial on shared memory with example code (if possible) that you can direct me to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有两种方法:
shmget
和mmap
。我将讨论mmap
,因为它更现代、更灵活,但您可以看一下man shmget
(或本教程)如果您更愿意使用旧式工具。mmap() 函数可用于分配具有高度可定制参数的内存缓冲区,以控制访问和权限,并在必要时使用文件系统存储来支持它们。
以下函数创建一个进程可以与其子进程共享的内存缓冲区:
以下是使用上面定义的函数来分配缓冲区的示例程序。父进程将写入一条消息,fork,然后等待其子进程修改缓冲区。两个进程都可以读写共享内存。
There are two approaches:
shmget
andmmap
. I'll talk aboutmmap
, since it's more modern and flexible, but you can take a look atman shmget
(or this tutorial) if you'd rather use the old-style tools.The
mmap()
function can be used to allocate memory buffers with highly customizable parameters to control access and permissions, and to back them with file-system storage if necessary.The following function creates an in-memory buffer that a process can share with its children:
The following is an example program that uses the function defined above to allocate a buffer. The parent process will write a message, fork, and then wait for its child to modify the buffer. Both processes can read and write the shared memory.
以下是共享内存的示例:
步骤:
使用 ftok 将路径名和项目标识符转换为 System V IPC 密钥
使用 shmget 分配共享内存段
使用shmat将shmid标识的共享内存段附加到调用进程的地址空间
对内存区域进行操作
使用shmdt分离
Here is an example for shared memory :
Steps :
Use ftok to convert a pathname and a project identifier to a System V IPC key
Use shmget which allocates a shared memory segment
Use shmat to attache the shared memory segment identified by shmid to the address space of the calling process
Do the operations on the memory area
Detach using shmdt
这些包括使用共享内存
These are includes for using shared memory
尝试这个代码示例,我测试了它,来源: http://www.makelinux.net/alp/035< /a>
try this code sample, I tested it, source: http://www.makelinux.net/alp/035
这是一个 mmap 示例:
Here's a mmap example:
我简化了 @salezica 的答案,以在父/子进程之间读/写共享
int
。还将包装函数重命名为
shared_malloc
。I simplified @salezica's answer to read/write a shared
int
between parent/child processes.Also rename the wrapping function to
shared_malloc
.