ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## Linux Hook机制研究 实现协程通信库时,如调用sleep, write,send等IO操作函数时,想要实现非阻塞高性能,需要用到Linux下的Hook机制,下面是简单研究过程。 ### 引子 在linux下调用C库中的函数,主要是调用得 `libc.so.6` 这个动态链接库中的函数。 那么我们有没有办法让应用程序改调其它函数,而应用程序无感知,Hook技术就是hack掉应用程序中调用的某些函数的一种技术手段。 ```cpp #include <stdio.h> #include <dlfcn.h> typedef unsigned int (*sleep_t)(unsigned int seconds); sleep_t sleep_f; #define DLSYM(name) \ name ## _f = (name ## _t)::dlsym(RTLD_NEXT, #name); struct HookIniter { HookIniter() { DLSYM(sleep); } }; static HookIniter hook_initer; unsigned int sleep(unsigned int seconds) { printf("sleep begin ...\n"); sleep_f(seconds); printf("sleep finish ...\n"); return 0; } int main() { sleep(1); return 0; } ``` 输出结果: ``` even@ubuntu:~/workspace/test/test$ g++ hook.cpp -ldl even@ubuntu:~/workspace/test/test$ ./a.out sleep begin ... sleep finish... ```