Compute this in C 1. Write a program in which the child process waits for parent
ID: 3607308 • Letter: C
Question
Compute this in C 1. Write a program in which the child process waits for parent process to complete some actions. The detailed actions are as follows (refer the procexec/fork sig_sync.c" which has reverse roles):40 points FILE NAME:hw5 1.c Before fork: a. Use SIGUSR1 and add this signal to the signal mask b. Use "signal()" to call "signal handler()" that prints out "Here is the Signal Handler Child process c. Suspend child process waiting for a signal from the parent d. Prints out "Child received a signal" e. Restore signal mask from the backup list f. Exit -Parent process g. Print out "Parent started... h. Sleep 3 seconds i. Print out "Parent about to signal child..." j. Send the SIGUSR1 to the child k. Exit
Explanation / Answer
To complete above task using C language follow the below program which covers all requirements which you mentioned in question.
//Header files to include
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
static volatile sig_atomic_t STOP = 0;
//Here Handles SIGUSR1
void signal_handler(int);
int main()
{
//And Add SIGUSR1 to signal mask
sigset_t OldSigSet;
sigset_t NewSigSet;
// set a SIGUSR1
sigaddset(&NewSigSet, SIGUSR1);
// unblock SIGUSR1 & backup old masks
sigprocmask(SIG_UNBLOCK, &NewSigSet, &OldSigSet);
// use signal() to call the signal_handler() that prints out "Here is the signal handler"
if (signal(SIGUSR1, signal_handler) == SIG_ERR)
{ perror("Failed to install SIGUSR1 handler"); exit(1); }
// creating child process.
int CHILD_PID = fork();
// from down here will be executed by both the parent and the child process.
// so we have to tell them exclusively what to do.
// in child CHILD_PID will be zero
if (CHILD_PID == 0) {
// suspend child process for a signal from the parent.
while(! STOP);
// revert to backup
sigprocmask(SIG_SETMASK, &OldSigSet, NULL);
}
else if (CHILD_PID > 0) { // if parent.
printf("Parent started... ");
// sleep 3 seconds
sleep(3);
printf("Parent about to signal child... ");
kill(CHILD_PID, SIGUSR1);
sleep(1);
}
else {
printf("Fork has been failed! Exiting ... ");
exit(1);
}
return 0;
}
/**
*It is Callback function for SIGUSR1
*/
void signal_handler(int signum)
{
printf("Child recieved the signal! ");
STOP = 1;
return;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.