击:招程序到标准输出的思维是一个互动终端 [英] Bash: trick program into thinking stdout is an interactive terminal

查看:129
本文介绍了击:招程序到标准输出的思维是一个互动终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行通过管道程序的输出,但它显然具有不同的行为检测时标准输出不是一个交互式shell。

I want to run a program's output through a pipe, but it apparently behaves differently when it detects stdout is not an interactive shell.

我怎么可以欺骗它变成通过管道写作只是因为它会在常规情况下?

How can I trick it into writing through the pipe just as it would in regular circumstances?

推荐答案

我认为程序会调用glibc的函数 isatty()为其来检查标准输出是一个终端或不。这是常见的对于使用上的ANSI终端像光标定位或擦除线/重画的终端或其​​他特征彩色输出的程序。

I assume that the program will call the glibc function isatty() to check whether stdout is a terminal or not. That's common for programs which use colorized output on terminals or other features of an ANSI terminal like cursor positioning or line erasing / redrawing.

您可以欺骗使用LD_ preLOAD环境变量的程序。 LD_ preLOAD被ELF链接器处理,并告知一个动态库应前所有其他被加载的。使用此功能就可以覆盖库函数,你的情况glibc的功能 isatty()为其。您可以按照例如本文章

You can trick the program using the LD_PRELOAD environment variable. LD_PRELOAD is handled by the ELF linker and tells that a dynamic library should be loaded before all others. Using this feature it is possible to override library functions, in your case the glibc function isatty(). You can follow this article for example.

我已经prepared了一个例子:

I've prepared an example for you:

首先创建文件的 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;
}

和编译为共享库:

gcc -shared -o libisatty.so  libisatty.c

它应建立精细。

现在是时候来测试库。 :)我用命令 LS --color =汽车做检查。 LS 通话 isatty()为其来决定是否应该着色其输出与否。如果输出重定向到文件或管道就不会进行着色。您可以测试这一点很容易使用下面的命令:

Now it's time to test the library. :) I've used the command ls --color=auto for tests. ls calls isatty() to decide whether it should colorize it's output or not. If the output is redirected to a file or a pipe it won't be colorized. You can test this easily using the following commands:

ls --color=auto        # should give you colorized output
ls --color=auto | cat  # will give you monochrome output

现在我们将尝试第二个命令再次使用LD_ preLOAD环境VAR:

Now we'll try the second command again using the LD_PRELOAD environment var:

LD_PRELOAD=./libisatty.so ls --color=auto | cat

您应该看到彩色输出。

You should see colorized output.

BTW酷USENAME:uʍopǝpısdn!!:D

btw cool usename: uʍop ǝpısdn !!:D

这篇关于击:招程序到标准输出的思维是一个互动终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆