3 ms·
> write_and_flush_to_dev_tty(BEGIN_RED_TEXT),write_and_flush_to_stdout("word"),write_and_flush_to_dev_tty(END_RED_TEXT); This isn't guaranteed to be serialized
by geocar 4y ago
> write_and_flush_to_dev_tty(BEGIN_RED_TEXT),write_and_flush_to_stdout("word"),write_and_flush_to_dev_tty(END_RED_TEXT);
This isn't guaranteed to be serialized: Someone trying to log the output of your application might try: | tee /dev/tty | logger ... or they might be running under kubernetes/docker (which does much the same thing).
I suggest the following:
1. If fd 0 and fd 1 are both ttys (isatty), and they point to the same tty (ttyname) then use it a tty (like your first example)
2. If fd 1 is not a tty, and fd 0 is a tty, write plaintext to fd 1. The user wants to filter output.
3. If neither fd 0 or 1 is a tty, write twice: do interactive stuff and send your vt-sequences with the text embedded to /dev/tty and a plaintext copy to fd 1.
Now the user doesn't need the extra tee, and we no longer need to worry about synchronisation. Users don't typically (meaningfully) grep interactive applications, so I think it's a good compromise for interactive servers and tuis.
But if you're not reading input or doing absolute cursor movement, and you just want some spicy log lines, I don't think you should be doing any of this fiddling: Just write sequences to stdout if it's a tty (or if the user specifically tells you to).
I also recommend checking for $NO_COLOR in the environment and honouring the users wishes here: Some users are colourblind so this represents a real accessibility issue for them. One of the advantages of ncurses/terminfo is you get some accessibility features you might not have known you needed.