Search code examples
cscanfstdin

Printf called before scanf inside forked process in C


I came across a problem using scanf inside a new process, created with fork(). Scanf is not blocked, so printf is called over and over.

Here is a sample of the code:

int main(int argc,char *argv[])
{
    switch(fork()) {
        case 0:
            while(1) {
                char buffer[100];
                scanf("%s",buffer);
                printf("Input was %s\n",buffer);
            }
    }
    return 0;
}

Does anybody know how to solve this simple problem? (some parts of code are missing, I shrinked the code to a minimum for this problem)


Solution

  • The problem is in the code that you commented out to make the minimal example, running this works perfectly fine

    #include <stdio.h>
    
    int main(int argc,char *argv[])
    {
        switch(fork()) {
            case 0:
                while(1) {
                    char buffer[100];
                    scanf("%s",buffer);
                    printf("Input was %s\n",buffer);
                }
                break;
            default:
                sleep(100);
                break;
        }
        return 0;
    }
    

    My guess is that with your full code around your fork call there is also some closing of files to create the subprocess and detach it from the terminal -- it is the closing of stdin and detachment from the terminal that makes you scanf fail.