I am a little confused write now. I have some code that #include <stdio.h> #incl
ID: 3527204 • Letter: I
Question
I am a little confused write now.
I have some code that
#include <stdio.h>
#include <stdlib.h>
main ()
{
int k;
printf ("Main Process' PID = %d ", getpid());
fflush(stdout);
for (k = 1; k <= 3; k++)
{
fork ();
printf ("k = %d, PPID = %d, pID = %d, I'm Alive! ", k, getppid(), getpid());
fflush(stdout);
}
}
When I run the program to the terminal I get
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!
[noecr@stu3 proj1]$ 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 teh 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 :
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?
Explanation / Answer
The fork function works like this #include main() { int pid, status, childPid; printf("I'm the parent process and my PID is %d ", getpid()); pid=fork(); /* Duplicate.*/ if (pid!=0) /* Branch based on return value from fork() */ { printf("I'm the parent process with PID %d and PPID %d. ", getpid(),getppid()); childPid=wait(&status); /* wait for a child to terminate */ printf("A child with PID %d terminated with exit code %d ", childPid, status>>8); } else { printf("I'm the child process with PID %d and PPID %d. ", getpid(),getppid()); exit(42); /* Exit with a silly number. */ } printf("PID %d terminates. ",pid); } $wait.exe ... run the program. I'm the parent process and my PID is 13464 I'm the child process with PID 13465 and PPID 13464. I'm the parent process with PID 13464 and PPID 13409 A child with PID 13465 terminated with exit code 42 PID 13465 terminates else try this and check it out how fork works! #include #include int main() { int pid = fork(); if (pid == 0) { printf("This is the child process. My pid is %d and my parent's id is %d. ", getpid(), getppid()); } else { printf("This is the parent process. My pid is %d and my parent's id is %d. ", getpid(), pid); } return 0; }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.