简体   繁体   中英

fgets causes C program to hang when run from bash on Windows, but works correctly when run from CMD or WSL

I'm following a 'Build your own Lisp' tutorial to teach myself C, and came across some strange behavior related to fgets. Here is a link to the Chapter I am working on: http://www.buildyourownlisp.com/chapter4_interactive_prompt#an_interactive_prompt

The code is a simple base for what will eventually be the REPL. It just prints some info, and then starts a loop that gets and prints user input.

#include <stdio.h>

static char input[2048];

int main(int argc, char** argv) {
        puts("Brenlisp Version 0.0.0.0.1");
        puts("Press Ctrl+c to Exit\n");

        while (1) {
                fputs("brenlisp> ", stdout);
                fgets(input, 2048, stdin);
                fputs(input, stdout);
        }

        return 0;
}

When I ran the executable from a Bash terminal (Windows 10), the program started but did not print anything to console, nor did it accept/print user input.

bschw@DESKTOP-92VUB1F MINGW64 ~/Projects/brenlisp
$ ./prompt.exe

However, when I ran the executable from CMD, the prompt performed as expected:

C:\Users\bschw\Projects\brenlisp>prompt.exe
BrenLisp Version 0.0.0.0.1
Press Ctrl+c to Exit

brenlisp> works fine
works fine
brenlisp> works fine
brenlisp> ^C
C:\Users\bschw\Projects\brenlisp>

Another curious thing is that when I run the program on WSL, it doesn't print the "^C" string to the console before exiting:

bschw@DESKTOP-92VUB1F:/mnt/c/Users/bschw/Projects/brenlisp$ ./prompt.exe
BrenLisp Version 0.0.0.0.1
Press Ctrl+c to Exit

brenlisp> works
works
brenlisp> works
brenlisp> bschw@DESKTOP-92VUB1F:/mnt/c/Users/bschw/Projects/brenlisp$

Why are these programs behaving differently depending on which shell they're being run from? How could I get the program to work properly on Bash?

In many implementations, the C Standard Library buffers output in internal buffers (*).

Often, for text streams, it does "line buffering" (buffers get emptied after dealing with a '\\n' ). This appears to be your case. Your output des not contain a newline.

To force the buffers to be emptied, use fflush() for output operations.

printf("not a line");
fflush(stdout);             // force buffer emptying

printf("complete line\n");  // line-buffering poses no issue here

(*) input streams may also be buffered, but the management of buffering for input is quite different

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM