z7ph1r z7ph1r - 1 month ago 20
C++ Question

How do Multi-process use the same ncurses screen?

I'm writing a c++ multi-process program with ncurses.

Each process is required to display something on the screen.

My Example code:

int main() {
initscr();
noecho();
curs_set(0);

int flag = fork();
if (flag == -1)
exit(1);
else if (flag == 0) {
WINDOW *win = newwin(4, 4, 0, 0);
int n = 0;
while (1) {
mvwprintw(win, 0, 0, "%d", n % 9);
wrefresh(win);
n = (n + 1) % 9;
sleep(1);
}
}
else {
WINDOW *win = newwin(4, 4, 8, 8);
int n = 0;
while (1) {
mvwprintw(win, 0, 0, "%d", n % 9);
wrefresh(win);
n = (n + 1) % 9;
sleep(1);
}
}
endwin();

return 0;
}


But it can only display one process's information on the screen.

How can I solve it?

Answer

I have hacked about something ugly that roughly works but shows what the problems are. I suspect a single window manager process which other processes communicate with would be better - or some horrible set of mutexes.

#include <stdlib.h>
#include <unistd.h>
#include <curses.h>
int main() {
  initscr();
  noecho();
  curs_set(0);
    WINDOW *win0 = newwin(4, 4, 0, 0);
    WINDOW *win1 = newwin(4, 4, 8, 8);

  int flag = fork();
  if (flag == -1)
    exit(1);
  else if (flag == 0) {
    int n = 0;
    while (1) {
      mvwprintw(win0, 0, 0, "%d", n % 9);
      wrefresh(win0);
      wrefresh(win1);
      n = (n + 1) % 9;
      sleep(1);
    }
  }
  else {
    int n = 0;
    while (1) {
      mvwprintw(win1, 0, 0, "%d", n % 9);
      wrefresh(win1);
      wrefresh(win0);
      n = (n + 1) % 9;
      sleep(1);
    }
  }
  endwin();

  return 0;
}

enter image description here

Comments