日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux共享数据,使用Linux共享数据对象

發(fā)布時(shí)間:2024/7/5 linux 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux共享数据,使用Linux共享数据对象 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。