我正在进行标准重定向:
$ cat file.txt | /usr/bin/program
但是,如果我直接在终端中运行程序并复制粘贴输入时,程序的行为会有所不同。
当输入来自终端时,程序会显示进度条。无论如何,我都想要这个进度条。
简而言之,我该如何“欺骗”程序,让它认为输入来自终端并且不是从文件重定向过来的?
expect
程序;它会为您完成大部分必要的工作。posix_openpt()
接口相对较新(与其他列出的函数相比,Issue 6 而不是 Issue 4,Version 2)。如果您的系统没有 posix_openpt()
,则需要获取一本 Unix 书籍(可能是 Stevens 或 Rochkind)以查找如何打开 pty 的主端,或者仔细阅读系统手册。但是,上面链接的 posix_openpt()
的原理也可能有所帮助,它还提供了使用其他函数的指南。Linux 有 posix_openpt()
;Mac OS X 以及 BSD 系统通常也有。W Richard Stevens, Stephen A Rago Unix 环境高级编程, 第三版
Marc J Rochkind 高级 UNIX 编程, 第二版
--color=force
)。 - Jonathan Leffler您需要使用伪终端才能达到您想要的效果。'man pty' 将为您提供更多信息。
isatty()
来检查stdin/stdout是否为终端。这对于那些在终端上使用彩色输出或其他ANSI终端功能(如光标定位或行擦除/重绘)的程序很常见。isatty()
。/**
* 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;
}
Makefile
# 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=libisatty.so ls --color=auto | cat
您应该看到有色彩的输出。
/usr/bin/program file.txt
不能工作? - Explosion Pills/usr/bin/program < file.txt
? - squiguy