我有我的程序,它执行另一个进程(不是我的,将其视为黑匣子)。有没有办法检测该子进程的操作,例如 open()
和 close()
?
我特别感兴趣的是查找所有新创建的文件或现有文件,这些文件是为了创建而打开的(open()
的 O_CREAT
标志)。
最佳答案
工作方法是在我自己的共享库中重新定义open()
,并通过LD_PRELOAD
将其预加载到exec()
'ed进程中> 环境变量。感谢@alk 提供的方法。
重新定义的 open()
代码如下所示:
#include <fcntl.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <sys/types.h>
extern "C" {
int open(const char *pathname, int flags, ...) {
bool has_mode = false;
mode_t mode = 0;
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
has_mode = true;
va_end(ap);
}
using Fn = int (*)(const char * pathname, int flags, ...);
Fn new_open = reinterpret_cast<Fn>(dlsym(RTLD_NEXT, "open"));
// Do something useful.
if (has_mode) {
return new_open(pathname, flags, mode);
} else {
return new_open(pathname, flags);
}
}
} // extern "C"
唯一的问题是 fcntl.h
- 它可能对函数 open()
有一些令人讨厌的声明。您需要此文件来获取 O_CREAT
的定义。另一种方法是直接包含带有定义的文件:在我的例子中,它是文件 asm-generic/fcntl.h
。
关于c - 如何用 C 检测 Linux 上 exec'ed 子进程的文件事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24349570/