2

When I try to run this code on my terminal, I get the output "hello from X process" after my prompt:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

void forkexample() 
{
    pid_t pidTo;
    int status = 0;
    int x = 1;

    if (fork() == 0){
        printf("hello from child process %d\n",getpid());
    }
    else{
        printf("hello from the parent process %d\n",getpid());
    }
}
int main()
{
    forkexample();
    exit(0);
}

My question is why am I getting the "hello from child process" after the prompt?

Terminal screenshot

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
  • 1
    I'd guess it has to do with the fact that the parent process is exiting and not waiting for the child process to do what it needs. Child process initiates IO sequence to stdout while parent process decides to exit. Shell sees the foreground process has exited so it ouputs the PS1 and then the IO from the child process finishes and outputs after that. – Christian Gibbons May 21 '18 at 18:37
  • 1
    1. You run your program from the shell; 2. It forks. 3. parent process executes its printf; 4. parent process exits; 5. the shell prints the prompt with the path (because the foreground process finished); 6. the child process runs and prints its message. – FBergo May 21 '18 at 18:38

1 Answers1

3

Problem

Your parent process does not wait for the child process to finish its execution.

Basically your program exits & your shell prints the prompt when your child process is not yet done printing, so you get the output from the child after the prompt.

Solution

Use wait():

if (fork() == 0)
  {
    printf("hello from child process %d\n", getpid());
  }
else
  {
    wait(&status); // Wait for the child process
    printf("hello from the parent process %d\n", getpid());
  }

You can pass an int pointer to wait(), it will be used to store the child's exit status.

Community
  • 1
  • 1
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56