c - 包装可变参数函数

标签 c gcc variadic-functions

我正在尝试包装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/

相关文章:

当没有明确的命令时,C 套接字 HTTP 请求异步打印响应

即使满足条件,代码也不会进入 while 循环

c++ - 外部结构前向声明

gcc - Windows 下 Eclipse 的 GNU ARM 插件 - OpenOCD 未开始调试

linux - gcc中的大尺寸指针

c++ - 向 C 风格可变参数列表添加额外参数

C 程序两个日期之间的天数——输出稍微太高?

我们可以使用 gcov 在 C/C++ 源文件中找到可执行代码行吗

c++ - 为什么 while 循环内的可变模板函数不打印到控制台?

java - 结合 guava 的 ImmutableList 和 varargs