You can capture the output of any command on the terminal using the script
utility, which is often installed by default. It saves all of the output of your program to a file named typescript
, and does not interfere with the program. With Linux, you might run it as follows:
script -c ./a.out
(With other systems, such as OSX, you may not have the -c
option: there is no POSIX standard for script
).
However, you may find the results unexpected, since they would be mixed with escape sequences. For instance, running your program with TERM
set to vt100
, and showing non-printing characters in printable form using unmap
, I see this:
Script started on Thu 03 Dec 2015 08:09:15 PM EST
\n
\E(B
\E)0
\E[1;40r
\E[m^O
\E[?7h
\E[H
\E[Jlol\r
\E[40;1H\r
\E[?1l
\E>
\nScript done on Thu 03 Dec 2015 08:09:16 PM EST
\n
Rather than try to separate the message from the escape sequences, some programs (such as dialog
) intentionally write their messages on the standard error while using the standard output for screen updates. Or (using newterm
) you can reverse that, making it simple to obtain a message.
Here is a revised program using that approach:
#include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
static void
show(const char *msg)
{
printw("%s", msg);
if (!isatty(fileno(stdout)))
puts(msg);
}
int
main(int ac, char **av)
{
newterm(NULL, stderr, stdin);
show("lol");
getch();
endwin();
return (0);
}
The revised program:
- writes its message using a function
show
which writes to the screen and optionally writes the message
- it checks if the standard output is not a tty using
isatty
, i.e., you are redirecting the program's output. Without the check, the two (output and error) would both be written to the screen, messing it up.
- some minor cleanup was done: removing an unused variable, and an unnecessary call to
refresh
(since getch
already did that).
This command
lol=`./a.out`
will do the requested assignment to lol
without interfering with the screen updates.