且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在使用Linux***享库的同一进程的实例之间共享共享库(.so)中的全局变量?

更新时间:2022-05-25 05:07:09

最清楚地表达这一点:您不能完全按照自己的要求去做. Linux不支持共享由链接器列出的全局变量.该内存将位于不可共享的映射交换空间中.

To phrase this most clearly: you cannot do exactly what you asked. Linux does not support sharing of global variables that are laid out by the linker. That memory will be in unsharable mapped-to-swap space.

我可以提供的一般配方是:

A general recipe I can offer is this:

  1. 定义用于布置数据的结构.没有指针!只是偏移量.
  2. 第一个过程在/tmp中创建一个文件,并根据需要设置访问权限rw.用MAP_SHARED打开mmap.
  3. 随后的进程也将打开,并使用MAP_SHARED映射.
  4. 每个人都使用该结构来查找他们引用,阅读或编写的内容.
  5. 注意并发!

如果您真的只在乎父级并且是分叉的子级,则可以使用匿名映射而不用担心文件,并且可以将映射的位置存储在全局变量中(可以在子级中读取)

If you really only care about a parent and it's forked children, you can use an anonymous mapping and not bother with the file, and you can store the location of the mapping in a global (which can be read in the children).