Find the answer to your Linux question:
Results 1 to 2 of 2
I am a little confused right now. I have some code that Code: #include <stdio.h> #include <stdlib.h> main () { int k; printf ("Main Process' PID = %d\n", getpid()); fflush(stdout); ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Jan 2013
    Posts
    9

    fork() printf file redirection


    I am a little confused right now.

    I have some code that
    Code:
    #include <stdio.h>
    
    #include <stdlib.h>
    
    main ()
    
    {
    
    int k;
    
    printf ("Main Process' PID = %d\n", getpid());
    
    fflush(stdout);
    
    for (k = 1; k <= 3; k++)
    
    {
    
    fork ();
    
    printf ("k = %d, PPID = %d, pID = %d, I'm Alive!\n", k, getppid(), getpid());
    
    fflush(stdout);
    
    }
    
    }
    When I run the program to the terminal I get

    Code:
    k =1, PPID =25078, pID =25079. I'm Alive!
    
    k =1, PPID =25034, pID =25078. I'm Alive!
    
    k =2, PPID =25078, pID =25079. I'm Alive!
    
    k =2, PPID =25034, pID =25078. I'm Alive!
    
    k =3, PPID =25078, pID =25082. I'm Alive!
    
    k =3, PPID =25034, pID =25078. I'm Alive!
    
    k =2, PPID =25078, pID =25081. I'm Alive!
    
    k =3, PPID =1, pID =25079. I'm Alive!
    
    k =3, PPID =25079, pID =25083. I'm Alive!
    
    k =2, PPID =25079, pID =25080. I'm Alive!
    
    k =3, PPID =25081, pID =25084. I'm Alive!
    
    k =3, PPID =25080, pID =25085. I'm Alive!
    
    k =3, PPID =1, pID =25081. I'm Alive!
    
    k =3, PPID =1, pID =25080. I'm Alive!
    Which is what I expected when I run this code, becuase fork creates a child process that inherits the buffer from the parent, so when I flush it the printf statement is flushed to the terminal and the I'm alive statement is printed.

    What I am consued about is when I redirect the output

    when I run ./a.out > file

    I get :

    Code:
    Main Process' PID =25209
    
    k =1, PPID =25161, pID =25209. I'm Alive!
    
    k =2, PPID =25161, pID =25209. I'm Alive!
    
    k =3, PPID =25161, pID =25209. I'm Alive!
    What is heppening when I redirect the file?

  2. #2
    Linux Enthusiast
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    638
    The redirection is handled by the shell and not by the program, so the children do not inherit the redirection.

Posting Permissions

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