Search code examples
cprintffork

Strange fork() behavior (previous printf is recalled)


I'm trying to solve a school problem about simulating a store with one employee (parent process) and multiple customers (child processes). I've simplified the code below to highlight the problem I've encountered while testing:

#define N_CUSTOMERS 10

void employee() {
}

void customer(int id) {
    exit(0);
}

int main() {

    printf("working!");

    // create customers
    for(int i = 0; i < N_CUSTOMERS; i++)
        if(!fork())
            customer(i);

    // be employee
    employee();

    // end
    exit(0);
}

The output is (compiled using gcc -Wall -pthread store.c -o store):

working!working!working!working!working!working!working!working!working!working!

I expected the printf to only execute once by the parent process, however, there seems to be a print for each child process created.

What am I missing here?


Solution

  • printf uses line-buffered output. Since the string printed doesn't have '\n', it's not printed before fork(). On exit() the buffer is flushed, and this happens in parent and all the children.