Linux中不同共享库中的数据可见性
假设有一个程序将动态加载两个共享库,并且在库 A 中分配了一条消息。我想知道库 B 是否可以使用该消息。
编辑:由于它只是处于设计阶段,所以没有“真正的代码”。
在共享库 A 中:
void process()
{
msg_ptr = new message();
send(msg_ptr); //send the msg address to library B
}
在共享库 B 中:
void process()
{
recv(msg_ptr); // at this point how can library B access the msg address
}
Suppose there is a program which will dynamically load two shared library and there is a message allocated in library A. I want to know if it is possible for library B to use that message.
Edit: Since it is just in the design stage, there is no "real code".
in shared library A:
void process()
{
msg_ptr = new message();
send(msg_ptr); //send the msg address to library B
}
in shared library B:
void process()
{
recv(msg_ptr); // at this point how can library B access the msg address
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(编辑):好的,这个问题有点令人困惑,因为
send
和recv
意味着进程间通信,但情况似乎并非如此,所以:简短的回答:是的,哪个库(静态库或动态库)进行分配并不重要。它始终是进程范围的。
共享库意味着代码只存储在磁盘上一次,但在运行时根本没有任何意义(这会影响使用)。
分配并不关心它是从库还是应用程序代码完成的。每个进程只有一个堆,从中进行所有分配。该堆可以被该进程上下文中运行的所有代码访问,并且不能被任何其他进程访问(即使使用相同的代码)。事实上,
operator new
本身位于另一个共享库 (libstdc++.so
) 中,它只是从另一个共享库 (malloc
) 调用malloc
代码>libc.so)。每个共享库在每个进程中只出现一次,即使有多个其他共享库依赖于它(在某些特殊情况下,这在 Windows 上可能会有所不同)。在运行时,一个地址空间中的指针在另一个进程的地址空间中永远不会有效,因此在进程之间传递消息中的指针永远没有意义。不过,同一进程的不同线程之间是完全可以的。
(Edit): Ok, the question is somewhat confusing because the
send
andrecv
imply inter-process communication and it seems not to be the case, so:Short answer: Yes, it does not matter which library, static or dynamic, does the allocation. It is always process-wide.
Shared library means the code is stored on disk once, but does not mean anything at all (that would have effect on usage) at runtime.
Allocation does not care whether it's done from library or application code. Each process has just one heap from which it does all allocations. This heap is accessible by all code running in context of that process and never accessible by any other process (even if using the same code). In fact, the
operator new
itself lives in another shared library (libstdc++.so
) and it just callsmalloc
from yet another shared library (libc.so
). And each shared library appears only once in each process, even when more than one other shared library depends on it (this may in some corner cases be different on Windows).At runtime, pointer in one address space is never ever valid in address space in another process, so passing pointers in messages between processes makes no sense, ever. It is perfectly OK between different threads of the same process though.