Ncurses and Linux pipeline

前端 未结 2 1153
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 15:00

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 (|

相关标签:
2条回答
  • 2021-01-15 15:23

    By default, curses writes to the standard output, which is where your pipe goes. But there are two different initialization functions for curses: initscr and newterm. The latter lets you do what was asked, like this:

    #include <stdio.h>
    #include <ncurses.h>
    
    
    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;
    }
    

    Further reading: manual page for newterm and initscr.

    0 讨论(0)
  • 2021-01-15 15:28

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

    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.

    0 讨论(0)
提交回复
热议问题