Ncurses和Linux管道

我想用ncurses写一个简单的程序来显示一些数据。 然后,我希望程序以这样的方式写入stdout,然后我可以在命令行上使用管道(|)来管理一些数据。

我目前的尝试不起作用。 我可以使用’>’在文件中看到“GOT HERE”,但还有很多其他内容。 该程序也立即退出。

#include  #include  int main(int _argc, char ** _argv) { initscr(); /* Start curses mode */ printw("Hello World !!!"); /* Print Hello World */ refresh(); /* Print it on to the real screen */ getch(); /* Wait for user input */ printf("GOT HERE"); endwin(); /* End curses mode */ printf("GOT HERE"); return 0; } 

这是使用>的最终输出

 ^[[?1049h^[[1;29r^[(B^[[m^[[4l^[[?7h^[[H^[[2JHello World !!!^MGOT HERE^[[29;1H^[[?1049l^M^[[?1l^[>GOT HERE 

是否可以通过管道使用stdout并同时进行ncurses?

默认情况下,curses写入标准输出 ,这是管道所在的位置。 但是curses有两种不同的初始化函数: initscrnewterm 。 后者可以让你做出被问到的内容,如下所示:

 #include  #include  int main(int _argc, char ** _argv) { newterm(NULL, stderr, stdin); /* Start curses mode */ printw("Hello World !!!"); /* Print Hello World */ refresh(); /* Print it on to the real screen */ getch(); /* Wait for user input */ printf("GOT HERE"); endwin(); /* End curses mode */ printf("GOT HERE"); return 0; } 

进一步阅读: newterminitscr手册页。

现在已经5年了,你可能已经开始了,但这是我搜索结果中的首选,所以我想我会添加我找到的解决方案。 在尝试使用像上面的bash例子这样的代码中运行管道之后,我终于找到了一个用newterm命令向正确方向暗示的人。 唯一的技巧是打开一个新的tty并使用newterm而不是initscr:

 #include  #include  int main(int argc, char ** argv) { FILE *f = fopen("/dev/tty", "r+"); SCREEN *screen = newterm(NULL, f, f); set_term(screen); //this goes to stdout fprintf(stdout, "hello\n"); //this goes to the console fprintf(stderr, "some error\n"); //this goes to display mvprintw(0, 0, "hello ncurses"); refresh(); getch(); endwin(); return 0; } 

有了这个,您可以在任何地方管道stdout和stderr,但有一个ncurses会话。 我不确定它是多么便携,或者是否有任何其他捕获,只是很高兴找到一个有效的解决方案。