Write a C/C++ program called signal-parent.cpp that waits a brief period of time
ID: 3719705 • Letter: W
Question
Write a C/C++ program called signal-parent.cpp that waits a brief period of time (10 seconds; using the sleep function) to simulate a daemon process initializing and then waiting for an incoming request.
After this period, the parent process should fork/exec (don't use the system() function call) a child process (call it signal-child.cpp). The parent process should then sleep for a longer period of time (2 minutes).
The parent process should determine when the child process exits. The parent process should report the child's PID and it's return/exit status.
The child process should also sleep for a period of time (30 seconds) to simulate a child process performing some work on behalf of the user. After the child process wakes up, it should simply exit with a value of 53.
At each step, both processes should output an informational message to help us understand what is happening, such as the following:
parent: forking child
child: going to sleep
etc.
(This information would typically be written to a log file; you may simply write to stdout.)
Explanation / Answer
/*--------------------A Program That shows the Child Terminate status------------------------------------*/
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
int main(void)
{
int ret,cpid,status;
sleep(10); //Waiting for 10 sec to ensure that daemon process initialization done.
printf("Parent:Forking a child ");
ret = fork(); // Creating A Child process with fork System call.
if(ret==-1)
{
perror("Fork fails:");
exit(1);
}
else if(ret==0) // Child Process(signal-child).
{
printf("Child:going to sleep ");
sleep(30);//Child process wait time 30 Secs.
exit(53); // Exit from child with exit status 53.
}
else // Parenet process(signal-parent).
{
sleep(120);// Parent process wait time 2mins.
cpid=wait(&status);// Holding the Exit status of child in "Status" varaible.
if(WIFEXITED(status))
{
printf("Child Process terminated normally ");
printf("Exit status=%d ",WEXITSTATUS(status));
}
else if(WIFSIGNALED(status))
{
printf("Child Process terminated abnormally ");
printf("Exit status=%d ",WTERMSIG(status));
}
}
}
Output:
Parent:Forking a child
Child:going to sleep
Child Process terminated normally
Exit status=53
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.