Question: correct my code please i am having issues being able to get the child parent and grandchild id to come up when i run my

correct my code please i am having issues being able to get the child parent and grandchild id to come up when i run my code here is my code : #include
#include
#include
#include
using namespace std;
int main(){
pid_t pid; // Process ID
const char *message;
int n;
int exit_code;
cout "fork program starting
";
pid = fork();
switch (pid){
case -1:
cout "Fork failure!
";
return 1;
case 0: // Child process
{
message = "This is the child
";
n =5;
exit_code =9;
// Create grandchild process
pid_t grandchild_pid = fork();
if (grandchild_pid ==0){// Grandchild process
cout "Grandchild Process. ID: " getpid()
", Parent ID: " getppid()
", Grandparent ID: " getppid() endl;
exit(0); // Grandchild exits
} else {
// Child process waits for grandchild to finish
int grandchild_status;
wait(&grandchild_status);
cout "Grandchild finished, ID: " grandchild_pid endl;
}
break;
}
default: // Parent process
{
message = "This is the parent
";
n =3;
exit_code =0;
break;
}
}
// Both parent and child processes run this loop
for (int i =0; i n; ++i){
cout message;
sleep(1);
}
// Parent waits for the child process to finish
if (pid !=0){// Parent process
int stat_val;
pid_t child_pid;
child_pid = wait(&stat_val); // Wait for child
cout "Child finished: PID =" child_pid endl;
if (WIFEXITED(stat_val)){
cout "Child exited with code " WEXITSTATUS(stat_val) endl;
} else {
cout "Child terminated abnormally!" endl;
}
}
exit(exit_code);
}
correct my code please i am having issues being

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!