1

I use fork() in order to make different proccesses running and printing a simple message.The result of the code counfuses me though.. Take a look at the code:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <math.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <time.h>


int main(void)
{

    fork();
    fork();
    fork();
    fprintf(stderr,"hello world\n");

}

and the output is:

mario@ubuntu:~/OS$ ./main
hello world
hello world
hello world
hello world
hello world
hello world
mario@ubuntu:~/OS$ hello world
hello world

mario@ubuntu:~/OS$ 

Note that i execute the program at the first line of the terminal but the output is not what i expected. Please help me! Thanks in advance! Same things happen if fprintf is changed with printf("......")

EDIT:I cant understand why the prints are this way. Six before the terminal line one next to it and 1 after it...

user93353
  • 13,733
  • 8
  • 60
  • 122
JmRag
  • 1,443
  • 7
  • 19
  • 56
  • Did you look at how the `fork` function works? Try to guess why you have 8 times 'hello world' using 3 forks. Hint, 8=2^3. – gniourf_gniourf Nov 29 '12 at 18:08
  • I know this fact!My problem is not the 8 prints but that they are disrupted by the terminal command. I dont find it reasonable for the program to print 6 before, one next to terminal line (mario@ubuntu:~/OS$ hello world ) and one after.. – JmRag Nov 29 '12 at 18:23

2 Answers2

3

When the parent program exited, the shell running the parent program printed the shell prompt mario@ubuntu:~/OS$ on the screen. Any child program which had not printed it's hello world by then would be printed after the prompt. If you want the prompt to not appear before all the hello worlds, you need to make the parent wait for all it's child and grandchild programs to terminate.

Check this to see how to make parent wait.

Community
  • 1
  • 1
user93353
  • 13,733
  • 8
  • 60
  • 122
0

You are creating 8 processes. Each fork divides the process into two. It the original parent finishes the other processes my still be executing. Hence if the original process finishes executing the shell gets a go and prints the prompt despite the other processes are still executing.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127