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.
- 01-23-2013 #1Just Joined!
- Join Date
- Jan 2013
- Posts
- 9
fork() printf file redirection
I am a little confused right now.
I have some code that
When I run the program to the terminal I getCode:#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); } }
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.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!
What I am consued about is when I redirect the output
when I run ./a.out > file
I get :
What is heppening when I redirect the file?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!
- 01-23-2013 #2Linux User
- Join Date
- Jan 2005
- Location
- Saint Paul, MN
- Posts
- 398
The redirection is handled by the shell and not by the program, so the children do not inherit the redirection.


Reply With Quote
