JmRag
JmRag

Reputation: 1459

fork() and stderr with terminal

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...

Upvotes: 1

Views: 749

Answers (2)

Ed Heal
Ed Heal

Reputation: 59997

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.

Upvotes: 0

user93353
user93353

Reputation: 14039

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.

Upvotes: 3

Related Questions