c - 使用动态库时如何抑制输出?

标签 c dynamic-linking

我实际上有解决这个问题的方法,但我想知道是否有更巧妙的方法。

我需要使用 dlopen 将库加载到我的实用程序中,然后调用其中一个函数。

不幸的是,该函数将一大堆信息输出到 STDOUT 上,这是我不想要的。

我有一个不可移植的解决方案,我想知道是否有更好、更通用的解决方案可供我使用。

这是我的(注意:这是 C):

/*
 * Structure for retaining information about a stream, sufficient to
 * recreate that stream later on
 */
struct stream_info {
    int fd;
    fpos_t pos;
};
#define STDOUT_INFO 0
#define STDERR_INFO 1

struct stream_info s_info[2];
point_stream_to_null(stdout, &s_info[STDOUT_INFO]);
point_stream_to_null(stderr, &s_info[STDERR_INFO]);

void *output = noisy_function();

reset_stream(stderr, &s_info[STDERR_INFO]);
reset_stream(stdout, &s_info[STDOUT_INFO]);

/*
 * Redirects a stream to null and retains sufficient information to restore the stream to its original location
 *** NB ***
 * Not Portable
 */
void point_stream_to_null(FILE *stream, struct stream_info *info) {
    fflush(stream);
    fgetpos(stream, &(info->pos));
    info->fd = dup(fileno(stream));
    freopen("/dev/null", "w", stream);
}

/*
 * Resets a stream to its original location using the info provided
 */
void reset_stream(FILE *stream, struct stream_info *info) {
    fflush(stream);
    dup2(info->fd, fileno(stream));
    close(info->fd);
    clearerr(stream);
    fsetpos(stream, &(info->pos));
}

有什么建议吗?

最佳答案

我有一个建议,它允许您使用预处理器来实现可移植性,或者可能是“可移植性”。

如果你尝试类似的东西

#if defined __unix__
#define DEVNULL "/dev/null"
#elif defined _WIN32
#define DEVNULL "nul"
#endif

(忽略其他操作系统、else 大小写、错误指令等) 然后像以前一样重新打开文件

FILE *myfile = freopen(DEVNULL, "w", stream);

那么这可能会给你你想要的。

不过我还没有在家里尝试过这个。 “nul”文件存在;见/dev/null in Windows .您可以在 "Pre-defined C/C++ Compiler Macros" 获得预定义的宏。 .

关于c - 使用动态库时如何抑制输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4760201/

相关文章:

c++ - 如何更改 Eclipse 自动生成的标题注释?

c - 在 C 中使用 Realloc 的字符串

c - 如何使用 C 程序从 xml 文件中删除节点?

ios - 如何将 LC_LOAD_DYLIB 命令插入 Mach-O 二进制文件或将静态库加入现有二进制文件 (IOS)

c - 尝试在内存中构建目录树时出现指针问题

c - 需要深入解释fork和exec

c++ - 找不到共享库

linux - Linux内核如何确定ld.so的加载地址?

linux - 加载期间的转储过程内存布局

c++ - 在 Ubuntu 14.04 下与 `libopencv_highgui.so` 链接错误, `libtiff.so.5` 的奇怪结果