0

i am using ANSI C and OpenMPI library.

I have this code:

if(myRank == 0)
{
    printf("\n\tEnter bright: ");
    scanf("%d", &bright);
}

But when i run the program it first wait for key pressing (scanf) and then printf. I really don't know what is happening.

Thank you.

John Smith
  • 97
  • 2
  • 10
  • Perhaps if it is first waiting for a key press _before_ it prints `"\n\tEnter bright: "`, then you have some other code that is calling another `scanf()`, or similar that requires input, and will block until it happens. – ryyker Nov 09 '13 at 04:09

2 Answers2

1

This has little to do specifically with MPI and is a pretty normal Unix I/O behaviour. The standard output stream is line buffered, which means that nothing is being sent to the underlying I/O subsystem unless a new line is encountered in the stream or a flush operation is enforced.

Compare the following: printf("asdasd"); and printf("asdasd\n");. In the first case, asdasd is appended to the buffer of the stdout stream, but since there is no new line there, the buffer is not flushed and nothing is actually sent to the terminal. In the second case asdasd is appended to the output stream and then the presence of the new line results in an automatic flush, therefore asdasd<new line> is what you see immediately. As already shown by John Zwinck, fflush(stdout); can be used to forcefully flush the stream buffer.

Note that if you come from Windows backgroud, the standard output there is not line buffered and printf("asdasd"); does result in adsasd being outputted without a following explicit flush operation. But then, even on Windows, it is possible that the I/O redirection mechanism of MPI is line buffered.

Hristo Iliev
  • 72,659
  • 12
  • 135
  • 186
0

I first wonder if it even makes sense to use scanf in such a way (there will be multiple processes involved--how do we know or assume that any of them will be attached to your terminal/keyboard?). But anyway, try flushing after printing:

printf("\n\tEnter bright: ");
fflush(stdout);
scanf("%d", &bright);
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • You're welcome. If this answer solved your problem, please do accept it by clicking the checkmark on the left. – John Zwinck Nov 09 '13 at 04:49
  • Most MPI implementations redirect the IO of `mpirun`/`mpiexec` to the standard input and output of rank 0, therefore `if (rank == 0) { scanf(); }` makes perfect sense. One catch is that this behaviour is not imposed by the standard and is therefore non-portable. – Hristo Iliev Nov 09 '13 at 11:17