linux共享数据,使用Linux共享数据对象
Linux共享數(shù)據(jù)對(duì)象類似于windows中的動(dòng)態(tài)鏈接庫,其后綴通常為so.* (*為版本號(hào)),例如為我們所熟知的libpcap,它對(duì)應(yīng)的文件為/usr/lib/libpcap.so。如果程序中使用了某共享數(shù)據(jù)對(duì)象文件,需要在鏈接時(shí)指定gcc的鏈接參數(shù)。如使用libpcap庫時(shí),加入lpcap;使用POSIX Thread時(shí),加lpthread。原則就是當(dāng)庫文件為libname.so.*時(shí),相應(yīng)的鏈接參數(shù)為lname,當(dāng)然,libname.so.*文件或其自身的符號(hào)鏈接需要放在/lib或者/usr/lib或者LIB_LIBRARY_PATH環(huán)境變量指定的路徑下。
使用共享數(shù)據(jù)對(duì)象主要涉及一下四個(gè)函數(shù):
void *dlopen(const char *filename, int flag);
const char *dlerror(void);
void *dlsym(void *handle, char *symbol);
int dlclose(void *handle);
dlopen函數(shù)負(fù)責(zé)載入動(dòng)態(tài)連接庫文件,成功時(shí)返回動(dòng)態(tài)鏈接庫的句柄。flag參數(shù)為RTLD_LAZY時(shí)表示在執(zhí)行動(dòng)態(tài)鏈接庫文件時(shí)解析未被決議的符號(hào);為RTLD_NOW時(shí)表示在dlopen函數(shù)返回是解析未被決議的符號(hào)。dlsym函數(shù)根據(jù)動(dòng)態(tài)鏈接庫的句柄,返回名稱為symbol的函數(shù)指針。dlerror返回asci形式的錯(cuò)誤信息。dlclose負(fù)責(zé)將打開動(dòng)態(tài)鏈接庫的引用計(jì)數(shù)減一,僅當(dāng)引用計(jì)數(shù)為0時(shí),dlclose才執(zhí)行關(guān)閉句柄操作,這意味著相同的動(dòng)態(tài)鏈接庫文件可以被打開多次。
下面給一段演示程序:
sort.h
#ifndef _SORT_H_
#define _SORT_H_
void bubble_sort(int[], int);
#endif /* _SORT_H_ */
sort.c
#include "sort.h"
void bubble_sort(int elems[], int elem_count)
{
int tmp, i, j;
for (i = 0; i < elem_count - 1; i++)
for (j = 0; j < elem_count - i - 1; j++)
if (elems[j+1] < elems[j]){
tmp = elems[j];
elems[j] = elems[j+1];
elems[j+1] = tmp;
}
}
test.c
#include
#include
#include "sort.h"
int main()
{
int items[] = {2, 5, 6, 1, -2, 6, 2, 10};
void (*sort)(int[], int);
void *h;
int i;
h = dlopen("./libsort.so.1", RTLD_LAZY);
if (!h){
fprintf(stderr, "Failed to load sort.so\n");
exit(-1);
}
sort = dlsym(h, "bubble_sort");
if (!sort){
fprintf(stderr, "Failed to export function bubble_sort\n");
exit(-1);
}
sort(items, sizeof(items) / sizeof(items[0]));
for(i = 0; i < sizeof(items) / sizeof(items[0]); i++)
fprintf(stdout, "%d\t", items[i]);
fprintf(stdout, "\n");
dlclose(h);
return 0;
}
Makefile
CC=gcc
CFLAG=-rdynamic -ldl
TARGET_lIB_NAME=libsort.so.1
OBJECTS=libsort.so.1 *.o test
test: $(TARGET_lIB_NAME) test.o
$(CC) $^ $(CFLAG) -o $@
libsort.so.1: sort.c
$(CC) $< -shared -o $@
test.o: test.c
$(CC) -c $<
.PHONY: clean
clean:
rm -rf $(OBJECTS)
總結(jié)
以上是生活随笔為你收集整理的linux共享数据,使用Linux共享数据对象的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql中有sa_SA工作-mysql
- 下一篇: linux如何批量导出文件格式,Linu