csshscanffflush

No output over SSH before waiting for input via scanf()


I have a file called get_int.c on a remote Unix system, containing the following:

#include <stdio.h>

int main() {
    int input;

    printf("Give an integer: ");
    fflush(stdout);
    scanf("%d", &input);

    printf("Try again: ");
    scanf("%d", &input);

    printf("You said... %d\n", input);

    return 0;
}

I have a command to compile and run this file from my local WSL:

sshpass -f pass.txt ssh username@remote.host.address "cd path/to/file/ && gcc get_int.c && a.out"

When I execute this command, I successfully get the prompt Give an integer: and provide one and press enter. Then, however, I do not get the prompt Try again:. I can still type an integer (123) and press enter. When I do, it then prints Try again: You said... 123

As you can see, no printing occurs until I either fflush(stdout) or the program ends. Can I possibly modify my ssh command so that output goes to the local terminal without having to fflush before every scanf?


Solution

  • Output to stdout does not seem to be flushed when reading from stdin on your system in the specific circumstances described. You must flush stdout explicitly with fflush() before every call to scanf():

    #include <stdio.h>
    
    int main() {
        int input;
    
        printf("Give an integer: ");
        fflush(stdout);
        scanf("%d", &input);
    
        printf("Try again: ");
        fflush(stdout);
        scanf("%d", &input);
    
        printf("You said... %d\n", input);
    
        return 0;
    }
    

    Alternately, you can set the output stream as unbuffered and won't need to flush it at all:

    #include <stdio.h>
    
    int main() {
        int input;
    
        setvbuf(stdout, NULL, _IONBF, 0);
    
        printf("Give an integer: ");
        scanf("%d", &input);
    
        printf("Try again: ");
        scanf("%d", &input);
    
        printf("You said... %d\n", input);
    
        return 0;
    }