help with fork() command???

Hi ,
help me out
Generally If the fork() is executed successfully Unix will create identical copies address spaces and the execution starts from the next statement of the fork()

So, in such case
output of the following prog must be

#include<stdio.h>
{
printf("\nwelcome to");
fork();
printf("\nDiscussion");
}

O/P as per the theory:
------------

welcome to 
Discussion
Discussion

but O/p coming is

welcome to 
Discussion
welcome to 
Discussion

lets try like this :wink:

# cat justdoit.c
#include<stdio.h>
#include<string.h>
#include  <sys/types.h>
main()
{
char buf[128];
pid_t pid;

write(1, "Before Fork ", 12);
printf(" \n*********\n");
sleep(1);
write(1,"Welcome to  ",12);
printf(" \n\n");
sleep(3);
write(1,"Fork will executing soon", 22);
printf(" \n******************\n");
fork();
sleep(3);
pid = getpid();
sprintf(buf, "\nDiscussion is viewing from pid = %d\n",pid);
write(1, buf, strlen(buf));
printf(" \n");
sleep(1);
}
# gcc justdoit.c -o 1

firstly , main(parent) process is executing..

# ./1
root     11404 26043  0 16:12 pts/0    00:00:00 ./1 -> our parent process

output

Before Fork
*********
Welcome to

Fork will process soon
******************

// we use write() instead of printf for understanding what is going on..
because of printf() usually uses stdout buffer area for write the output
so i meant, printf() outputs will not be send to screen immediately //

when fork() process exucuted in your program , a child process is spawned by fork() and kernel
briefly,child process is copied in memory from the parent.

root     11404 26043  0 16:12 pts/0    00:00:00 ./1 -> parent process
root     11421 11404  0 16:12 pts/0    00:00:00 ./1 -> child process

and then "both processes" will execute the next instruction following the fork() system call

output

Discussion is viewing from pid = 11421 -> From Child


Discussion is viewing from pid = 11404 -> From Parent

regards
ygemici

1 Like

In short, printf() doesn't go directly to the screen -- it waits inside a memory buffer first. When you put a \n on the end, the buffer is flushed. Also, when the program quits, the buffer is flushed.

So, you are putting "welcome to" in the buffer and not printing it to screen before you fork().

The fork()ed process gets a copy of that buffer.

Then you print an \n in both, flushes the buffers in both. Not necessarily in any predictable order, just whenever each happens to be run!

Then they print the rest, quit, and flush again. Again, not necessarily in any predictable order!

If you must printf(), do fflush(stdout) before you fork().

1 Like

@Corona688
thanks