我正在写一个程序,从stdin读取input,操纵input,并将输出写入标准输出。 然而,很多程序检查stdin是否是terminal或pipe道(通过调用isatty类的函数),并生成不同的输出。 我如何让自己的程序假装成TTY?
该解决scheme应该可以在Linux和MacOS上运行。 任何生成独立二进制文件的编程语言都是可以接受的,但Go是首选。
请注意,我正在问一个编程问题,而不是要求一个工具。 所以,像script或unbuffer这样的东西不是我正在寻找的东西。
如何在Windows控制台中正确输出string?
是否有可能使用Go编译器分发其他操作系统的可执行文件?
在RaspBerry Pi上安装Go软件包
如何在golang发送窗口的系统通知
如何启用docker的udev同步成功?
Golang插件热重新加载
如何在Go中pipe理Windows用户帐户?
golang opengl windows安装问题
为什么由exec.Start()创build的进程退出,如果它的父母被SIGINT杀死?
以下是在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); 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) > 0 && FD_ISSET(master,&fds)) { bytes_read = read(master,buf,buf_size); if (bytes_read <= 0) { return EXIT_SUCCESS; } if (write(STDOUT_FILENO,bytes_read) != bytes_read) { perror("Failed to write to stdout"); return EX_OSERR; } } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。