'Why is sleep in a child process blocking my program?

So I have this simple program that sleeps for 4 second if the value returned by fork is '0' meaning that the child process is executing, I've tried using sleep in child process but the program is blocked, and flushing standard output isn't working... code:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char const *argv[]) {
  pid_t value = fork();

  if (value == 0) {
    sleep(4);
  }
  
  printf("Value returned by fork: %d\n", value);
  printf("I'm the process N°%d\n", getpid());
  
  return 0;
}

I'm running on Ubuntu 20.04.3 LTS.

Output:

Value returned by fork: 12618
I'm the process N°12617\
farouk@farouk-HP-Pavilion-Desktop-TP01-1xxx:~/sysexp$  Value returned by fork: 0
I'm the process N°12618

enter image description here



Solution 1:[1]

To allow this question to have an accepted answer.

The child process is not blocking the shell. The shell gave its prompt and the child wrote some output after the prompt, leaving the cursor at the start of a line without a shell prompt visible — because the shell prompt already appeared earlier.

There are a variety of ways around this.

The simplest is just to type a command such as ps and hit return, noting that the shell executes it, and that the ps output does not list the child process. If you type the ps command quick enough, you might see the child listed in the output before its output appears.

Another is to modify the program so that it waits for all child processes to exit before it exits — using wait() or waitpid(). The same code can be used in the child and the parent since the child will have no children of its own. The call to the wait function will return immediately with a 'no more children' status (error).

You can find extensive discussion of all this in the comments — I've chosen to make this a Community Wiki answer since there was a lot of activity in the comments that identified the gist of this answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1