编写假装是TTY的程序

我正在写一个程序,从stdin读取input,操纵input,并将输出写入标准输出。 然而,很多程序检查stdin是否是terminal或pipe道(通过调用isatty类的函数),并生成不同的输出。 我如何让自己的程序假装成TTY?

该解决scheme应该可以在Linux和MacOS上运行。 任何生成独立二进制文件的编程语言都是可以接受的,但Go是首选。

请注意,我正在问一个编程问题,而不是要求一个工具。 所以,像scriptunbuffer这样的东西不是我正在寻找的东西。

以下是在pty中运行命令并捕获其输出的完整工作代码。 (不像你想象的那么多)。

 #include <signal.h> #include <stdlib.h> #include <sysexits.h> #include <unistd.h> #include <util.h> pid_t child = 0; void sighandler(int signum) { if (child > 0) { killpg(child, signum); exit(signum); } } // Run a command in a pty. // Usage: /path/to/this/binary command to run int main(int argc, char *argv[]) { if (argc < 2) { return EX_USAGE; } int master; child = forkpty(&master, NULL, NULL, NULL); if (child == -1) { perror("failed to fork pty"); return EX_OSERR; } if (child == 0) { // we're in the child process, so replace it with the command execvp(argv[1], argv + 1); perror("failed to execute command"); return EX_OSERR; } // trap kill signals and forward them to child process signal(SIGHUP, sighandler); signal(SIGINT, sighandler); signal(SIGTERM, sighandler); const int buf_size = 1024; char buf[buf_size]; fd_set fds; ssize_t bytes_read; // forward the output continuously while (1) { FD_ZERO(&fds); FD_SET(master, &fds); if (select(master + 1, &fds, NULL, NULL, NULL) > 0 && FD_ISSET(master, &fds)) { bytes_read = read(master, buf, buf_size); if (bytes_read <= 0) { return EXIT_SUCCESS; } if (write(STDOUT_FILENO, buf, bytes_read) != bytes_read) { perror("failed to write to stdout"); return EX_OSERR; } } } }