I'm still not able to solve that question (Q6 of Lab1). To convey you where exactly I'm getting stuck, I'll post the 2 programs, which I wrote for Q4 & Q6 respectively (with help from ChatGPT) below:
#include "common.h" // to output in order of creation, use wait() inside 1st for loop [experiment with lines 17 & 22]
int main() {
int pid, status;
for (int i=0; i<10; i++) { // Loop to create 10 children
if ((pid = fork()) < 0) {
perror("fork failed");
exit(1);
}
if (pid == 0) { // Child process
printf("Child %d: PID = %d\n", i+1, getpid());
exit(0); // Child exits
}
// wait(&status);
}
// parent process
for (int i=0; i<10; i++){
if((pid = wait(&status)) < 0){
perror("wait failed");
exit(1);
}
printf("parent freed child with PID %d \n", pid);
}
printf("All children freed. Parent exiting.\n");
return 0;
}
********************************************************************
The above is the program for Q4. Can you please verify if it's correct?
**********************************************************************
#include "common.h"
int main() {
int pid, status;
srand(time(NULL)); // Seed random number generator
for (int i=0; i<10; i++) { // Loop to create 10 children
if ((pid = fork()) < 0) {
perror("fork failed");
exit(1);
}
if (pid == 0) { // Child process
sleep(rand() % 20);
printf("Child %d: PID = %d\n", i+1, getpid()); // Child i is the i-th child created
exit(0); // Child exits
}
}
// parent process
for (int i=0; i<10; i++){
if((pid = wait(&status)) < 0){
perror("wait failed");
exit(1);
}
printf("parent freed child with PID %d \n", pid);
}
printf("All children freed. Parent exiting.\n");
return 0;
}
***************************************************************
The above is the program for Q6, where I just added a sleep() to that of Q4, as you suggested earlier. I can clearly see from the output of this program that the free up order and the creation order are not same. But, how do I know if the free up order and the termination order are the same? In particular, how do I keep track of the termination order in my above program? [If this is outside our midsem syllabus, then please don't bother answering. I'll skip it for now & retry when we cover those concepts later]