Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

c - Ncurses and Linux pipeline

I'd like to write a simple program using ncurses for displaying some data. I would then like for the program to write to stdout in such a way that I can then use a pipe (|) on the command line to pipe some data out.

My current attempt doesn't work. I can see the "GOT HERE"'s in a file using '>', but there's a whole bunch of other stuff. The program also exits immediately.

#include <stdio.h>
#include <ncurses.h>


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;
}

This is the final output using >

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

Is it possible to use stdout through a pipeline and ncurses at the same time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is 5 years old now and you've probably moved on, but this was the top of my search results so I thought I'd add the solution I found. After a lot of messing about with trying to get pipes to work in code like bash example above, I finally found someone that hinted in the right direction with the newterm command. The only trick is to open a new tty and to use newterm instead of initscr:

#include  <stdio.h>
#include <ncurses.h>

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
");
  //this goes to the console
  fprintf(stderr, "some error
");
  //this goes to display
  mvprintw(0, 0, "hello ncurses");
  refresh();
  getch();
  endwin();

  return 0;
}

With this you can pipe stdout and stderr wherever you want but have an ncurses session. I'm not sure how portable it is or if there are any other catches, just glad to find a solution that worked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...