1

我希望能够通过命令替换调用基于 ncurses 的程序,以便其输出可以作为命令行参数传递给另一个程序。例如,当程序没有进入 curses 模式时,这在 bash 中很容易做到:

echo $(pwd) # should be the same as just calling pwd alone

当我尝试使用我的程序(其代码如下)执行此操作时,永远不会进入诅咒模式,并且永远不会打印字符串“test”。进入 curses 模式很重要,因为从理论上讲,用户会以某种方式操纵最终打印到 stdout 的字符串(现在该字符串只是静态的)。

echo $(./a.out) # just prints an empty line

我的程序在进入curses模式后正常运行时会返回字符串“this is not a test”,“test”打印到屏幕上,用户按下一个键。

./a.out # normal run

这是有问题的代码:

// test.cpp
#include <ncurses.h>
#include <iostream>
using namespace std;

/* get curses up and running */
void init() {
    initscr(); // start curses mode, might clear screen
    raw(); // disable line buff, and C-z/C-c won't gen sigals; see cbreak()
    keypad(stdscr, TRUE); // enable arrow keys and function keys
    noecho(); // don't echo chars user types
}

/* shut curses down */
void end() {
   endwin(); // end curses mode
}

int main()
{
    init();
    printw("test");
    getch();
    end();

    cout << "this is not a test" << endl;
    return 0;
}

我用这个命令编译:

g++ test.cpp -lcurses

谢谢您的帮助!

4

1 回答 1

2

这是一个简单的解决方案,使用newterm

#define _XOPEN_SOURCE
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    // start curses mode
    SCREEN* s = NULL;
    FILE* out = stdout;
    if(!isatty(fileno(stdout))) {
        out = fopen("/dev/tty", "w");
        // Should really test `out` to make sure that worked.
        setbuf(out, NULL);
    }
    // Here, we don't worry about the case where stdin has been
    // redirected, but we could do something similar to out
    // for input, opening "/dev/tty" in mode "r" for in if necessary.
    s = newterm(NULL, out, stdin);

    printw("test");
    getch();

    endwin(); // end curses mode
    delscreen(s);
    puts("/home/matt");
    return 0;
}
于 2013-07-03T16:48:02.233 回答