Unix 中的共享内存
我正在 Unix 中创建一个守护进程,它将独占访问串行端口“/dev/tty01”。我计划创建一个主从进程范例,其中有一个主站(守护进程)和多个从站。
我正在考虑在“共享内存”中建立一个奴隶可以访问的结构,并且内存中只有一个写入者,所以我很可能不需要信号量。数据更新速度相当慢,例如每分钟更新一次。
我正在研究什么是最好的方法来做到这一点,如果我在共享内存中有一个结构,我如何保证该结构在内存中是连续的?这是我必须具备的要求。
谢谢
I am creating a Daemon in Unix that will have exclusive access to a serial port "/dev/tty01". I am planning to create a Master - Slave process paradigm where there is one master (the daemon) and multiple slaves.
I was thinking of having a structure in "Shared memory" where the slaves can access, and there is only one writer to the memory so I most likely wont need a semaphore. The data will be updated fairly slowly, once every minute for example.
I was looking into what would be the best possible way to do this, also if I have a structure in shared memory, how can I guarantee that the structure will be contiguous in memory? It is a requirement I must have.
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,共享内存会很困难,因为您需要在主机写入时锁定读取器,并在仍有读取器时让写入器等待。
更容易的是让主控写入临时文件(在同一目录中)并在准备好后将其重命名为最终名称(重命名是原子的)。
这假设客户端定期 open() 和 fstat() 文件来检查自上次读取以来是否已触及该文件。
另一种方法是避免使用文件,让主机只维护自己的内部数据结构并打开一个(侦听)套接字,该套接字在 open() 上只吐出它当前拥有的所有数据。无需锁定。
Shared memory will be hard in this case, because you'll need to lock out the readers when the master is writing, and keep the writer waiting when there still are readers.
Easier would be to have the master to write to a temp file (in the same directory) and rename it to the final name once ready (rename is atomic).
This assumes the client to periodically open() and fstat() the file to check if it was touched since the previous read.
Yet another way would be to avoid files, and let the master just maintain its own internal data structures and have a (listen) socket open, which on open() just spits out all the data it currently has. No locking needed.