简体   繁体   English

提高共享内存的有效性

[英]Boost Shared Memory validity

I'm using Boost Shared Memory to share a vector across processes. 我正在使用Boost共享内存跨进程共享向量。

In the client, how can I, once I try and open the shared memory and read a vector off it, realize if the memory is not valid, or is not what I'm looking for. 在客户端中,一旦我尝试打开共享内存并从中读取一个向量,我怎么能知道该内存无效或不是我要的内容。

Will the Open_Only fail if the memory segment does not exist, and if so, how do I catch this failure? 如果内存段不存在, Open_Only是否会失败?如果存在,我如何捕获此失败?

Also, the shared memory segment is supposed to be removed, if there are no references to it. 同样,如果没有引用,则应该删除共享内存段。 However, in my case, even when both the client and server are shut down, and nothing else is accessing the shared memory, the segment remains in Boost Interprocess folder in Program data, with some data. 但是,就我而言,即使客户端和服务器都关闭了,并且没有其他东西在访问共享内存,该段仍保留在Program数据的Boost Interprocess文件夹中,其中包含一些数据。 So the next time client starts up, it has no problem opening up the segment, and so thinks it is accessing correct data when in fact, there is no data to be shared. 因此,下一次客户端启动时,打开段没有问题,因此认为实际上没有数据要共享时,它正在访问正确的数据。

Kindly advise. 好心提醒。 Thank you. 谢谢。

Speaking from experience with the underlying shm api--and not as a Boost expert... 从基础shm api的经验讲起-而不是作为Boost专家...

To determine validity, one technique is to figure out if the current process is the one that is creating the shared memory (the first time). 为了确定有效性,一种技术是确定当前进程是否是第一次创建共享内存的进程。 You can do this by getting the size after creating (fstat) and seeing if the size is zero. 您可以通过在创建(fstat)之后获取大小并查看大小是否为零来实现。 If it is zero, the process is creating it. 如果为零,则表明该进程正在创建。 Once you know that you can initialize it. 一旦知道可以对其进行初始化。 Also, when you call truncate() to set the size here, that size is set for all other processes. 同样,当您调用truncate()在此处设置大小时,将为所有其他进程设置该大小。

To ensure removal, you can call shm_unlink() to remove the shared memory file from the system. 为了确保删除,您可以调用shm_unlink()从系统中删除共享内存文件。 I believe in Boost there is a remove() api that will do that. 我相信在Boost中有一个remove()API可以做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM