Ç的Linux:全局变量位于共享库单 [英] C Linux: Global variable located in shared library as singleton

查看:122
本文介绍了Ç的Linux:全局变量位于共享库单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用位于共享库(。所以)作为一个单独的全局变量,如果库由多个进程?

Is it possible to use global variable located in a shared library (.so) as a singleton if the library is used by more than one process?

作为例如初始值为0,过程递增该变量,然后PROC2递增VAL并打印。

As example the initial value is 0, process 1 increments the var then proc2 increments the val and prints it.

我的实验,到目前为止表明,这两个过程保持变量的副本,如果第一个增量是第二个将仍然读取0,所以行为是不喜欢的Windows DLL ...

My experiments so far showed that the both process keep copies of the variable and if 1st increments it the second will still read 0. So the behavior is not like Windows DLLs...

我这里一文中读到,如果全局变量的的静态(在lib)和它的声明为在lib头中的VAR是所有工艺的独特EXTERN。但到目前为止,我还没有能够做到这一点 - VAR仍然为每个进程复制

I read in one article here that if the global variable is not static (in the lib) and it's declared as extern in the lib header the var is unique for all the process. But so far I haven't been able to accomplish this - var is still copy for each process.

有人可以提供这很好的解释?而如何做到这一点...

Can someone please offer good explanation of this? And how to do it...

推荐答案

,任何modifyable数据仍然私有的过程。有喜欢的写入时复制机制的相同数据时,只要它是只读共享的,但只要它是由两个过程中写的复制。所以,对于每一个处理所述数据有效仍然是分开的。另请参见共享库的地址空间

If a shared library (or a Windows DLL) is used by more than one process, any modifyable data is still private to the process. There are mechanisms like Copy on Write where the same data is shared as long as it is only read, but copied as soon as it is written by either process. So, for each process the data effectively is still separate. See also shared library address space.

如果你想在进程间共享数据,您需要使用共享内存并确保访问共享存储器在进程之间的同步。

If you want to share data between processes, you need to use Shared Memory and make sure that access to the shared memory is synchronized between the processes.

这篇关于Ç的Linux:全局变量位于共享库单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆