Search code examples
cregexprintfposixflush

Why don't regexec(), regcomp(), followed by print statements execute immediately?


I have a functioning HTTP server coded in C. In my quest to add regex functionality to it I've encountered strange functionality of my program. My main function looks like this:

int main(void)

{
    char *example = "index.html";
    regex_t REGEXhtml;
    int mond = 1;
    if(regcomp(&REGEXhtml, ".html", 0)){printf("REGEX error 1"); return -1;}
    mond = regexec(&REGEXhtml, example, 0, NULL, 0);
    if(!mond) {printf("FOUND HTML");}
    printf("%i", mond);

    //......server code ........
}

For some reason, when executing this code after compilation the print statements will NEVER be printed and my program will seemingly idle infinitely. This is expected behavior without the above code, since my server will idle in the terminal and wait for a connection, then log it to the terminal. Unexpectedly, the program isn't just hanging there. When someone connects to my server, the printf statements are printed as they should, followed by my server logging printf statements.

As this goes against my current understanding of programming, I researched this problem a little bit and found the following from the man page:

│regcomp(), regexec() │ Thread safety │ MT-Safe locale

and the attributes link describes this as meaning:

   locale Functions annotated with locale as an MT-Safety issue read
          from the locale object without any form of
          synchronization.  Functions annotated with locale called
          concurrently with locale changes may behave in ways that
          do not correspond to any of the locales active during
          their execution, but an unpredictable mix thereof.

Does that accurately explain the above behavior? I'm rather confused how having these functions can seemingly delay the execution of my print statements, especially the last one. And if that description is related, what are the technicalities of what exactly is happening here, both during execution and compilation?

Edit: So DannyNiu below fixed my simple mistake, but I'm still interested in an example of the MT-Safety locale and its implications on other parts of code. If anyone has examples or links to explanations please post/comment below


Solution

  • stdout (thus printf) is fully buffered unless libc detects it's outputting to a terminal window, in which case it's line-buffered.

    Try adding newline characters to the end of the output string, or adding fflush calls.