Operating Systems Programming question: (35 points) A parent process and a child
ID: 3911245 • Letter: O
Question
Operating Systems Programming question:
(35 points)
A parent process and a child process use kill() and signal to communicate. Please use fork() to create the child process from the parent. After that, the parent process can then send the following signals to the child process using kill():
SIGHUP: hang-up (death) on controlling terminal (process) (Default action: abnormal termination)
SIGINT: interactive attention signal (usually Ctrl-C) (Default action: abnormal termination)
SIGQUIT: interactive termination: core dump (Default action: implementation dependent)
The parent process can sleep() some time (for example, 5 seconds) after sending each signal.
The child process:
After receiving SIGHUP: output “I have received SIGHUP”;
After receiving SIGINT: output “I have received SIGINT”;
After receiving SIGQUIT: output “I have received SIGQUIT”, and terminate.
Here is the pseudocode for this program:
A list of functions defining the actions associated with signals
Main()
1. Create the child process;
2. if (child process)
{
Use signal() or sigaction() to specify the action associated with the signal;
Infinite loop;
}
3. if (parent process)
{
Send SIGHUP to the child process;
Sleep some time;
Send SIGINT to the child process;
Sleep some time;
Send SIGQUIT to the child process;
Sleep some time;
}
For more examples, please refer to Chapter 8 of the following textbook:
Unix System Programming, K.A. Robbins and S. Robbins, Prentice Hall, ISBN: 0-13-042411-0, 2003
Explanation / Answer
The process sleeps for 5 seconds after receiving each signal.
Here is the working code:
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/shm.h>
// #include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void sighup(int); /* routines child will call upon sigtrap */
void sigint(int);
void sigquit(int);
void main(void)
{
signal(SIGHUP,sighup); /* set function calls */
signal(SIGINT,sigint);
signal(SIGQUIT, sigquit);
int pid;
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}
if(pid==0){
for(;;); /* loop for ever */
}
else {
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
/* parent */
/* pid hold id of child */
printf(" PARENT: sending SIGHUP ");
kill(pid,SIGHUP);
sleep(5); /* pause for 5 secs */
printf(" PARENT: sending SIGINT ");
kill(pid,SIGINT);
sleep(5); /* pause for 5 secs */
printf(" PARENT: sending SIGQUIT ");
kill(pid,SIGQUIT);
sleep(5);
}
}
void sighup(int signo) {
signal(SIGHUP,sighup); /* reset signal */
printf("CHILD: I have received a SIGHUP ");
}
void sigint(int signo) {
signal(SIGINT,sigint); /* reset signal */
printf("CHILD: I have received a SIGINT ");
}
void sigquit(int signo) {
printf("I have received SIGQUIT ");
exit(0);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.