我正在尝试包装open
函数。我不知道如何将可选的第三个参数传递给真正的open
。据我了解,无法验证 va_list ,因此下面示例中的 if (mode) 不正确。有没有办法使用适当数量的参数来调用 open
?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>
extern "C"
{
int shouldWrap = 0;
int willCallRealOpen(const char * path, int flags, va_list args);
int __real_open(const char * path, int flags, ...);
int __wrap_open(const char * path, int flags, ...) {
if(shouldWrap != 0){
printf("Fake called\n");
return 0;
}
else {
printf("Real called\n");
va_list args;
va_start(args, flags);
int res = willCallRealOpen(path, flags, args);
va_end(args);
return res;
}
}
int willCallRealOpen(const char * path, int flags, va_list args) {
mode_t mode = va_arg(args, mode_t);
if (mode) {
printf("3 args\n");
return __real_open(path, flags, mode);
}
else {
printf("2 args\n");
return __real_open(path, flags);
}
}
}
int main() {
//int fd = open("temp.txt", O_CREAT | O_WRONLY, S_IRUSR);
int fd = open("temp.txt", O_CREAT | O_WRONLY);
}
最佳答案
open 的手册页显示:
mode specifies the permissions to use in case a new file is created. This argument must be supplied when O_CREAT or O_TMPFILE is specified in flags; if neither O_CREAT nor O_TMPFILE is specified, then mode is ignored.
所以我认为你应该这样做:
int willCallRealOpen(const char * path, int flags, va_list args) {
if (flags & (O_CREAT | O_TMPFILE))
{
mode_t mode = va_arg(args, mode_t);
printf("3 args\n");
return __real_open(path, flags, mode);
}
else {
printf("2 args\n");
return __real_open(path, flags);
}
}
关于c - 包装可变参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40418964/