LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-25-2011, 03:56 PM   #1
mayjune
LQ Newbie
 
Registered: Jan 2011
Posts: 4

Rep: Reputation: 0
Question Why fork is executing the program twice from start???


Hi,
I am learning about OS and I wrote this simple forking program...
Here's the code..

Code:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
        pid_t pid;

        printf ("\n\n~~~~~~~~~~~~At the start of the programm..... My pid  = %d and my parent id = %d", getpid(), getppid());

        pid = fork();

        printf ("\nforked done my pid = %d and my parent pid = %d\n", getpid(), getppid());

        if (pid < 0)
        {
                fprintf (stderr, "Fork Failed");
                return -1;
        }


        else if (pid == 0)
        {
                printf("\n\nhello i am a child process my pid = %d and my parent pid = %d\n", getpid(), getppid());
        }

        else
        {
                wait(NULL);
                printf ("\n\nWait Complete my pid = %d and my parent pid = %d\n", getpid(), getppid());
        }

        return 0;
}
Now the problem is, first statement - At the start of the programm..... is being printed twice!!!!!

Here's the final output

Code:
mankaj@mankaj:~$ cc new2forking.c -o new2forking
mankaj@mankaj:~$ ./new2forking 


~~~~~~~~~~~~At the start of the programm..... My pid  = 4239 and my parent id = 1762
forked done my pid = 4239 and my parent pid = 1762
~~~~~~~~~~~~At the start of the programm..... My pid  = 4239 and my parent id = 1762
forked done my pid = 4240 and my parent pid = 4239


hello i am a child process my pid = 4240 and my parent pid = 4239


Wait Complete my pid = 4239 and my parent pid = 1762
mankaj@mankaj:~$
How can it print the first statement, that is BEFORE the fork() statement twice????


I am really confused. What am I doing wrong? Or is it suppose to be this way?

I am running Natty 11.04 btw..

Thanks a lot for your help
 
Click here to see the post LQ members have rated as the most helpful post in this thread.
Old 05-25-2011, 04:27 PM   #2
clvic
Member
 
Registered: Feb 2008
Location: Rome, Italy
Distribution: OpenSuSE 11.x, vectorlinux, slax, Sabayon
Posts: 206
Blog Entries: 2

Rep: Reputation: 45
Yes this is really confusing... but try editing the first printf, add a "\n" at the end, like this:
printf ("\n\n~~~~~~~~~~~~At the start of the programm..... My pid = %d and my parent id = %d\n", getpid(), getppid());

You won't get the message repeated twice. That's because a printf without a "\n" accumulates the characters in a buffer. Then, the fork clones the buffer itself along with the whole process.
Finally, as soon as the buffer is emptied (because of a "\n" in your case), then all messages are printed out, the old ones along with the new ones.
 
4 members found this post helpful.
Old 05-25-2011, 05:14 PM   #3
PinoyAko
LQ Newbie
 
Registered: May 2011
Posts: 28

Rep: Reputation: 0
Quote:
Originally Posted by clvic View Post
Yes this is really confusing... but try editing the first printf, add a "\n" at the end, like this:
printf ("\n\n~~~~~~~~~~~~At the start of the programm..... My pid = %d and my parent id = %d\n", getpid(), getppid());

You won't get the message repeated twice. That's because a printf without a "\n" accumulates the characters in a buffer. Then, the fork clones the buffer itself along with the whole process.
Finally, as soon as the buffer is emptied (because of a "\n" in your case), then all messages are printed out, the old ones along with the new ones.

VPN for Android
That was something new. Thanks for answering his question because I also learned from this

Last edited by PinoyAko; 12-17-2011 at 03:53 AM.
 
Old 05-25-2011, 05:36 PM   #4
mayjune
LQ Newbie
 
Registered: Jan 2011
Posts: 4

Original Poster
Rep: Reputation: 0
Oh my GOD!!!
I can't believe that!!! How in the world you knew that??? lol I mean that is Soooo Not Obvious!!!
Thanks a ton. I kept looking at the program for so long....had no clue what to do...

Is there anything else that I "should" be aware of, such obsure stuff that you won't expect to happen!!!!??

Thanks a lot....you saved tons of hours for me....
 
Old 05-25-2011, 05:52 PM   #5
mayjune
LQ Newbie
 
Registered: Jan 2011
Posts: 4

Original Poster
Rep: Reputation: 0
Ok how about this.... i have only removed the \n at the end of the bolded line...

Code:
int main()
{
        pid_t pid;

        printf ("~~~~~~~~~~~~At the start of the programm..... My pid  = %d and my parent id = %d", getpid(), getppid());

        pid = fork();

        printf ("\n\nforked done my pid = %d and my parent pid = %d", getpid(), getppid());
And the output is


Code:
mankaj@mankaj:~$ cc new2forking.c -o new2forking
mankaj@mankaj:~$ ./new2forking 
~~~~~~~~~~~~At the start of the programm..... My pid  = 3077 and my parent id = 2948

~~~~~~~~~~~~At the start of the programm..... My pid  = 3077 and my parent id = 2948

forked done my pid = 3078 and my parent pid = 3077

hello i am a child process my pid = 3078 and my parent pid = 3077
forked done my pid = 3077 and my parent pid = 2948

Wait Complete my pid = 3077 and my parent pid = 2948
Why the order has changed? What \n makes the buffer empty? First \n or last \n of a printf statement? I didn't get this part...

Thanks a lot..
 
Old 05-25-2011, 08:56 PM   #6
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,659
Blog Entries: 4

Rep: Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940
Quote:
Originally Posted by mayjune View Post
Oh my GOD!!!
I can't believe that!!! How in the world you knew that??? lol I mean that is Soooo Not Obvious!!!
Thanks a ton. I kept looking at the program for so long....had no clue what to do...

Is there anything else that I "should" be aware of, such obsure stuff that you won't expect to happen!!!!??

Thanks a lot....you saved tons of hours for me....
The old guy looks at you with a brief, dumbfounded stare, but quickly recovers. He pushes himself back from the desk in his cube and leans forward, pointing to a slightly rough spot on his now-glistening cranium. "Believe it or not, young'un, at one time way back then I still had hair, and that spot right there is where I yanked quite a bit of it out ... (little did I know at the time how much I'd miss it) ... solving a problem that's almost exactly like yours." He cracks a surprisingly youthful smile. "And that is why I spend a part of my day, every day, on linuxquestions.org."
 
Old 05-26-2011, 05:45 AM   #7
mayjune
LQ Newbie
 
Registered: Jan 2011
Posts: 4

Original Poster
Rep: Reputation: 0
Quote:
Originally Posted by sundialsvcs View Post
The old guy looks at you with a brief, dumbfounded stare, but quickly recovers. He pushes himself back from the desk in his cube and leans forward, pointing to a slightly rough spot on his now-glistening cranium. "Believe it or not, young'un, at one time way back then I still had hair, and that spot right there is where I yanked quite a bit of it out ... (little did I know at the time how much I'd miss it) ... solving a problem that's almost exactly like yours." He cracks a surprisingly youthful smile. "And that is why I spend a part of my day, every day, on linuxquestions.org."
Lol....
 
Old 05-28-2011, 05:47 AM   #8
clvic
Member
 
Registered: Feb 2008
Location: Rome, Italy
Distribution: OpenSuSE 11.x, vectorlinux, slax, Sabayon
Posts: 206
Blog Entries: 2

Rep: Reputation: 45
Quote:
Originally Posted by mayjune View Post
Why the order has changed? What \n makes the buffer empty? First \n or last \n of a printf statement? I didn't get this part...

Thanks a lot..
I think this depends on the specific implementation of the printf, depending on your version of C... I bet the buffer usually flushes at the last "\n" of a printf call.
The order in which you see the prints from the processes also depends on the scheduler, so it can't be considered reliable.

Quote:
Is there anything else that I "should" be aware of, such obsure stuff that you won't expect to happen!!!!??
Well, the answer is difficult, so I can only suggest reading a good book... I found this reference on how a fork should behave on the web, this seems quite explanatory:
http://pubs.opengroup.org/onlinepubs...ions/fork.html
 
1 members found this post helpful.
Old 05-28-2011, 09:12 PM   #9
Nominal Animal
Senior Member
 
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
Blog Entries: 3

Rep: Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948
Quote:
Originally Posted by mayjune View Post
Code:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
        pid_t pid;

        printf ("\n\n~~~~~~~~~~~~At the start of the programm..... My pid  = %d and my parent id = %d", getpid(), getppid());
At this point, before forking, you need to make sure all pending output is output. Add
Code:
        fflush(stdout);
        fflush(stderr);
to explicitly flush both standard output and standard error streams.

Quote:
Originally Posted by mayjune View Post
How can it print the first statement, that is BEFORE the fork() statement twice????
At fork() time, all memory structures are duplicated. This includes any data pending in output buffers. Since the statement was in the output buffer for standard output (as noted by civic, above), both processes will include the first statement in their output when they finally flush the buffers.

Add explicit fflush() for each open output stream before fork() calls to avoid this situation.

Last edited by Nominal Animal; 05-28-2011 at 09:14 PM.
 
1 members found this post helpful.
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] fork behaviour......what is the output of this program vivignesh Linux - Newbie 9 07-06-2010 05:11 PM
C program that fork a son, and... lumacho Programming 1 11-12-2009 08:58 AM
Problem with fork() in cgi program klopfer Programming 6 03-30-2007 08:57 AM
Executing a program on start up andrewthk Debian 3 03-23-2006 12:49 AM
How to fork a program and tell when it's done? tonyfreeman Programming 5 09-01-2004 10:25 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:09 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration