Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program, signals.c that will utilize signal handlers to intercept keyboa

ID: 3870248 • Letter: W

Question

Write a program, signals.c that will utilize signal handlers to intercept keyboard interrupts to manage control of a child process. Your main program should fork and exec a new child process to run the "yes" command (use man yes to learn more). You should then register signal handlers for both ctrl-c and ctrl-z in your main program. The ctrl-z signal handler should toggle the child yes stop the child process if it is running, or resume the child process if it is stopped, all while keeping the main program running. The ctrl-c signal should kill the child process, and then exit the main process. In both signal handlers, add print statements indicating what the program is doing- i.e. "ctrl-z caught, stopping child process". Your main program should sit in an infinite loop once the setup has been completed. It should only exit when the user hits ctrl-c, after cleaning up the child process.

Explanation / Answer

#include<stdio.h>
#include<signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

int pid;

void sig_handler(int signo)
{
static int stop;

if (signo == SIGINT) {
printf("received SIGINT.. Sending kill signal to the child ");
kill(pid, SIGKILL);
printf("Done ");
exit(0);
}

if (signo == SIGTSTP) {
printf ("Child pid :: %d ", pid);
if (!stop) {
printf("Ctrl z caught Stopping child process ");
kill(pid, SIGSTOP);
stop = 1;
} else {
printf("Ctrl z caught Resuming child process ");
kill(pid, SIGCONT);
stop = 0;
}
}
}

int main (int argc, char **argv)
{
printf ("Parent: Hello, World! ");
if (signal(SIGINT, sig_handler) == SIG_ERR)
printf(" can't catch SIGINT ");

if (signal(SIGTSTP, sig_handler) == SIG_ERR)
printf(" can't catch SIGINT ");

pid = fork();

if (pid == 0) {
printf("I am the child ");
execv ("/usr/bin/yes", NULL);
}

while (1)
sleep(1);

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote