如何在c中的两个程序之间共享库 [英] How can I share library between two program in c

查看:20
本文介绍了如何在c中的两个程序之间共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C 中的两个不同程序中使用相同的库函数(即 OpenSSL 库)进行计算.如何确保两个程序都使用一个公共库,这意味着 只有 一个库副本被加载到 共享主内存 并且两个程序都从该内存位置访问该库计算?

I want to use same library functions (i.e. OpenSSL library ) in two different programs in C for computation. How can I make sure that both program use a common library , means only one copy of library is loaded into shared main memory and both program access the library from that memory location for computation?

例如,当第一个程序访问库进行计算时,它从主内存加载到缓存中,当第二个程序想要稍后访问它时,它将访问缓存中的数据(已经被第一个程序加载),不是再次从主内存中.

For example, when 1st program access the library for computation it is loaded into cache from main memory and when the 2nd program wants to access it later , it will access the data from cache ( already loaded by 1st program), not from main memory again.

我在 Linux 下使用 GCC.任何解释或指针将不胜感激.

I am using GCC under Linux. Any explanation or pointer will be highly appreciated .

推荐答案

阅读 Drepper 的论文 如何编写共享库程序库方法

Read Drepper's paper How to Write Shared Libraries and Program Library HowTo

要制作一个,请将您的代码编译为 位置无关代码,例如

To make one, compile your code as position independent code, e.g.

 gcc -c -fPIC -O -Wall src1.c -o src1.pic.o
 gcc -c -fPIC -O -Wall src2.c -o src2.pic.o

然后将其链接到共享对象中

then link it into a shared object

 gcc -shared src1.pic.o src2.pic.o -lsome -o libfoo.so

你可以将一个共享库 -lsome 链接到另一个 libfoo.so

you may link a shared library -lsome into another one libfoo.so

在内部,动态链接器 ld-linux.so(8) 正在使用 mmap(2) (和会在动态链接时做一些 relocation),重要的是 inode.内核将使用文件系统缓存来避免两次读取不同进程使用的共享库.另请参阅 linuxatemyram.com

Internally, the dynamic linker ld-linux.so(8) is using mmap(2) (and will do some relocation at dynamic link time) and what matters are inodes. The kernel will use the file system cache to avoid reading twice a shared library used by different processes. See also linuxatemyram.com

使用例如ldd(1), pmap(1)proc(5).另请参阅 dlopen(3).试试

Use e.g. ldd(1), pmap(1) and proc(5). See also dlopen(3). Try

cat /proc/self/maps

了解地址空间.虚拟内存">process 运行该 cat 命令;并非 ELF 共享库的所有内容都在进程之间共享,只有一些段,包括 文本段...

to understand the address space of the virtual memory used by the process running that cat command; not everything of an ELF shared library is shared between processes, only some segments, including the text segment...

这篇关于如何在c中的两个程序之间共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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