Linux下利用dlopen()+dlsym()實現單元測試中系統調用的mock(2)

還有一種情況,一些系統調用所在的庫並不在默認的路徑或者調用定義不在默認的庫中,此時需要我們指定庫的查找路徑和庫名稱,比如mock rt庫中的系統調用,具體查看以下代碼:

#include <dlfcn.h>
#include <time.h>

const std::string rt_path = "/usr/lib/x86_64-linux-gnu/librt.so";
void *create_handler = NULL;
// mock timer_create
typedef int (*timer_create_func_t)(clockid_t clockid, struct sigevent *sevp,
                                   timer_t *timerid);
                           
extern "C" int timer_create(clockid_t clockid, struct sigevent *sevp,
                            timer_t *timerid) {
  create_handler = dlopen(rt_path.c_str(), RTLD_NOW | RTLD_GLOBAL);
  if (create_handler == NULL) {
    return -1;
  }
  timer_create_func = reinterpret_cast<timer_create_func_t>(dlsym(create_handler, "timer_create"));
  if (timer_create_func == NULL) {
    return -1;
  }
return timer_create_func(clockid, sevp, timerid);
}

其他庫或者其他系統調用也是一樣,找到所在庫以及庫所在路徑,按照上述方法實現即可,可以在函數體中自定義的添加一些分支,根據不同需求,返回不同的值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章