我假设程序会调用 glibc 函数isatty() 来检查 stdin/stdout 是否是终端。这对于在终端上使用彩色输出或 ANSI 终端的其他功能(如光标定位或行擦除/重绘)的程序来说很常见。
您可以使用 LD_PRELOAD 环境变量来欺骗程序。 LD_PRELOAD 由 ELF 链接器处理,并告诉动态库应该在在所有其他库之前加载。使用此功能可以覆盖库函数,在您的情况下为 glibc 函数 isatty()。
这里有一个例子:
libisatty.c
/**
* Overrides the glibc function. Will always return true.
*
* Note: Although this should be ok for most applications it can
* lead to unwanted side effects. It depends on the question
* why the programm calls isatty()
*/
int isatty(int param) {
return 1;
}
生成文件
# Make the shared Library
lib: libisatty.c
gcc -shared -Wl,-soname,libisatty.so.1 -o libisatty.so.1.0 libisatty.c
ln -s libisatty.so.1.0 libisatty.so.1
ln -s libisatty.so.1 libisatty.so
运行:
make lib
应该没问题,我在 Ubuntu12.04 AMD 64 上测试过。
现在是测试库的时候了。 :) 我使用命令ls --color=auto 进行测试。 ls 调用 isatty() 来决定它是否应该着色它的输出。如果输出被重定向到文件或管道,它将不会被着色。您可以使用以下命令轻松测试:
ls --color=auto # should give you colorized output
ls --color=auto | cat # will give you monochrome output
现在我们将使用 LD_PRELOAD 环境变量再次尝试第二个命令:
LD_PRELOAD=libisatty.so ls --color=auto | cat
您应该会看到彩色输出。