3 Comments

  1. Title should be “How to print a line to stderr OR stdout in C++?” as I was looking for how to print to both at the same time.

    1. I guess the “and” in the title should be the “and” in “buy an apple and a banana” rather than the “&&” in “a && b” ;-)

      If you want to print to STDOUT && STDERR **atomically**, it will be an interesting problem. The operations of printing a line to STDOUT or STDERR themselves are not atomic operations.

      One way that is close to that may be to use a producer/consumer like printing mechanism:

      – one buffer using an array like data structure for holding each item/line to be printed out and 2 status marks for each item
      – 2 threads waiting for the buffer content and print them to STDOUT and STDERR each; after prints it, the thread sets that corresponding buffer status
      – 1 cleaner thread to clean the items if both statuses are set

      The printing function writes the item/line to be printed out to the buffer.

      The outputs to STDERR and STDOUT may run in parallel though not strictly synchronized or atomically.

Leave a Reply

Your email address will not be published. Required fields are marked *