1

If I launch a background process that uses MPI as follows:

system("start \"\" cmd /k \"cd <path> && mpiexec -n 1 <exe> &\"");

it works fine, but the entire output is shown in the command prompt at the end of the program. I would like to see the output immediately as it is being printed. How do I do that? Note that if I don't use mpiexec in the command, I correctly get the output as soon as it happens.

Sample:

#include <iostream>
#include <windows.h>
#include <mpi.h>
#include <cstdio>

int main(int argc, char* argv[])
{
    MPI_Init(&argc, &argv);

    printf("test A\n");
    Sleep(2000);

    printf("test B\n");
    Sleep(2000);

    printf("test C\n");
    Sleep(2000);

    MPI_Finalize();
    return 0;
}

Edit: Using fflush(stdout) to flush the output after every print statement fixes the issue (as mentioned in the comments). However I would like to know if there is any other way to fix this, since this would require changing thousands of print statements in the code.

Moody
  • 1,037
  • 1
  • 11
  • 16
  • 1
    Where are you using `printf`? – Tommy Andersen Dec 05 '17 at 12:57
  • I meant I'm using printf in the c++ application I'm trying to run – Moody Dec 05 '17 at 13:13
  • 1
    Are you flushing the output of the application? You should probably write the code that prints the output from the application. – Tommy Andersen Dec 05 '17 at 13:20
  • I didn't know I had to flush output when using printf, I thought that was only necessary with c++ streams. I can't post the application code, it's a very large application with printf statements strewn all over the place. They're just regular calls to printf, with '\n' at the end. – Moody Dec 05 '17 at 13:42
  • @TommyAndersen Moody should *definitely* show *some* code. Look [here](https://stackoverflow.com/help/mcve). Make a (new) `main()` function with some `printf`'s. – TobiMcNamobi Dec 05 '17 at 14:16
  • Okay when I was trying to create a minimal example, I found the issue occurs when I use mpiexec to launch the application, which I forgot to mention. I edited the question to reflect that. – Moody Dec 05 '17 at 15:14
  • Apparently mpiexec sets stdout to something that's not a character device, such as a pipe or disk file. In this case stdout defaults to full buffering. You can manually disable buffering of stdout at startup by calling `setvbuf(stdout, NULL, _IONBF, 0)`. This way you don't have to flush after every print. – Eryk Sun Dec 05 '17 at 19:35

0 Answers0