Strange behaviour of fork function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manjuscripts
    New Member
    • Aug 2007
    • 6

    Strange behaviour of fork function

    The output of the below program is "hihi" as "hi" is printed by both parent and child process
    [code=c]
    #include<stdio. h>
    main()
    {
    printf("hi");
    fork();
    }
    [/code]

    where as the output below program is
    [code=c]
    #include<stdio. h>
    main()
    {
    printf("hi\n"); //observe the \n after hi
    fork();
    }
    [/code]
    is only "hi"

    what's the reason?
    Last edited by sicarie; Aug 29 '07, 05:04 PM. Reason: Code tags
  • mac11
    Contributor
    • Apr 2007
    • 256

    #2
    Originally posted by manjuscripts
    The output of the below program is "hihi" as "hi" is printed by both parent and child process

    #include<stdio. h>
    main()
    {
    printf("hi");
    fork();
    }


    where as the output below program is

    #include<stdio. h>
    main()
    {
    printf("hi\n"); //observe the \n after hi
    fork();
    }

    is only "hi"

    what's the reason?
    your printing BEFORE the fork - so there is only 1 process to print "hi"
    try
    Code:
    fork()
    printf( "hi\n");

    Comment

    • manjuscripts
      New Member
      • Aug 2007
      • 6

      #3
      Originally posted by mac11
      your printing BEFORE the fork - so there is only 1 process to print "hi"
      try
      Code:
      fork()
      printf( "hi\n");

      but why it's printing "hihi" in first program? i think there's something related to "\n" or buffer.

      Comment

      • svlsr2000
        Recognized Expert New Member
        • Feb 2007
        • 181

        #4
        Originally posted by manjuscripts
        but why it's printing "hihi" in first program? i think there's something related to "\n" or buffer.
        Yes you are right. Printing in linux is implemented in such a way that nothing is printed till it encounters some special characters like '\n' or till program is about to terminate.

        Once it is passed to stdin, buffer is cleared. But this buffer is also part of your address space so when you fork even this buffer is copied. Resulting in printing Hi twice.

        Comment

        Working...