Find the answer to your Linux question:
Results 1 to 10 of 10
Hi, Code: if (fork() == 0) printf ("Child\n"); printf ("Parent\n"); What will be printed when this piece of code is executed?...
  1. #1
    Just Joined!
    Join Date
    Dec 2007
    Posts
    2

    Fork Output in child and parent

    Hi,
    Code:
    if (fork() == 0)
             printf ("Child\n");
    printf ("Parent\n");
    What will be printed when this piece of code is executed?

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    This sounds a bit like a homework question, in which case I suggest you try running it for yourself.

    The way fork() works is that it spawns a child process, returns 0 in that child, and returns the child's PID (guaranteed to be a positive, non-zero number) in the parent (assuming no errors, in which case no child is spawned, and -1 is returned).

    So in this instance, you will note the call to fork, creating a child process. In the parent, fork() will be a positive number, while in the child, it will be 0.

    Can you figure out what will happen?
    DISTRO=Arch
    Registered Linux User #388732

  3. #3
    Just Joined!
    Join Date
    Nov 2007
    Posts
    9
    Result would be:
    Child
    Parent

  4. #4
    Just Joined!
    Join Date
    Dec 2007
    Posts
    2
    Quote Originally Posted by Cabhan View Post
    This sounds a bit like a homework question, in which case I suggest you try running it for yourself.
    It's not a homework question, I'm just trying to figure out how a fork() call returns.
    And I tried it before, it printed Child once and then Parent twice. I just want to know the sequence of executing statements in the original processs and the forked one.
    (Why was "Parent" printed twice?)

  5. #5
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    Ah, okay. Just wanted to be sure.

    The reason for this is that fork() returns twice, with separate return values. So let's follow what happens after fork() returns:

    Child
    fork() returns 0. The if condition is true, so I will print "Child". I then continue to the next instruction, which tells me to print "Parent".

    Parent
    fork() returns some positive, non-zero number. The if condition is false, so I continue to the next instruction, which tells me to print "Parent".

    This is why "Parent" is printed twice. What you might like to do is something like:
    Code:
    pid_t cpid = fork();
    if(cpid < 0)
    {
        fputs("ERROR!  fork() failed!\n", stderr);
        exit(1);
    }
    else if(cpid == 0)
        puts("Child");
    else
        puts("Parent");
    As for the order of execution of statements, there is no guarantee of any sort. It could happen in any way. Often, the parent relies on the child to do something, so it is rather common to see code like:
    Code:
    pid_t cpid = fork();
    if(cpid < 0)
    {
        fputs("ERROR!  fork() failed!\n", stderr);
        exit(1);
    }
    else if(cpid == 0) /* child */
    {
        /* let the child do some work */
        exit(0);
    }
    else /* parent */
        waitpid(cpid, NULL, 0);
    
    /* when we get here, the child is finished and gone, and only the parent exists */
    Do you understand why this works?
    DISTRO=Arch
    Registered Linux User #388732

  6. #6
    Just Joined!
    Join Date
    Nov 2007
    Posts
    9
    emmm...........I understand now...thanks

  7. #7
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    Quoth the highly esteemed Cabhan:
    As for the order of execution of statements, there is no guarantee of any sort. It could happen in any way.
    Not so! Not so! O how the might have fallen! Bwahahahahahaha.

    We know that the originally posted code snippet will not produce:
    Code:
    Parent
    Parent
    Child
    Yeah, yeah, yeah, I know whatcha meant, but still and all! Victory is still victory, regardless of the triviality thereof!!!!!1!!!!111!!!leventy-leven!! When you get to be my age, you young whippersnapper, you'll stoop to anything to get it! (Victory, I mean.)
    --
    Bill

    Old age and treachery will overcome youth and skill.

  8. #8
    Linux Guru Lakshmipathi's Avatar
    Join Date
    Sep 2006
    Location
    3rd rock from sun - Often seen near moon
    Posts
    1,568

    Thumbs up

    This is Strange ,
    I tried to execute above code just added a printf before forking
    see
    Code:
    main(){
    printf("Before calling Fork()\n");
    if (fork() == 0)
             printf ("Child\n");
    printf ("Parent\n");
    }
    The output is expected one:
    Code:
    [oss@pc021698 ~]$ ./a.out
    Before calling Fork()
    Child
    Parent
    Parent
    But when i remove the newline char from printf i got different output

    Code:
    main(){
    printf("Before calling Fork()");
    if (fork() == 0)
             printf ("Child\n");
    printf ("Parent\n");
    }
    Output:
    see Before calling fork() is printed twice
    Code:
    [oss@pc021698 ~]$ ./a.out
    Before calling Fork()Child
    Parent
    Before calling Fork()Parent
    I'm using FC4 and gcc version is 4.0.0 20050519

    Any thoughts-why this \n makes such a difference in output?
    - Lakshmipathi.G
    -------------------
    FOSS India Award winning ext3fs Undelete tool and tutorials www.giis.co.in
    First they criticize you,Then they laugh at you,Then they fight with you,Then you win. - M.K.Gandhi
    -------------------

  9. #9
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    This has to do with the way that IO works. Basically, when you print something, it is not printed immediately. Rather, it is saved to a buffer, and when the buffer is sufficiently full (or when you intentionally flush it), the buffer as a whole is printed. This cuts down tremendously on the number of writes performed, which means much better performance.

    Now, when a newline is printed, the buffer is generally flushed. Alternatively, you can call fflush(FILE *) to flush a buffer.

    The reason for the duplication is that fork() copies buffer contents. In the first instance, where the newline is printed, the buffer is flushed after that print statement. Therefore, there is no buffer to copy, and all is well.

    However, when no newline is printed, the buffer contains "Before calling Fork()". The buffer ends up getting flushed only after "Child" or "Parent" is printed, meaning that both copies of the process have this in their buffer, and it is printed twice, as expected.

    IO buffering is a crazy, crazy world.
    DISTRO=Arch
    Registered Linux User #388732

  10. #10
    Linux Guru Lakshmipathi's Avatar
    Join Date
    Sep 2006
    Location
    3rd rock from sun - Often seen near moon
    Posts
    1,568
    thanks a lot Cabhan for valuable information of IO buffering
    - Lakshmipathi.G
    -------------------
    FOSS India Award winning ext3fs Undelete tool and tutorials www.giis.co.in
    First they criticize you,Then they laugh at you,Then they fight with you,Then you win. - M.K.Gandhi
    -------------------

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...