Create a C ++ (Linux/Unix) program that handles the sending and receiving of sig
ID: 3849074 • Letter: C
Question
Create a C ++ (Linux/Unix) program that handles the sending and receiving of signals. Have the program fork itself and have the child send signals (via kill) to the parent. Send at least three different types of signals, though you don't want to send signals such as INTR, KILL, STOP. Create the signal handling functions for those signals you send. Here is a little code to get you started.
struct sigaction *action = new (struct sigaction);
action->sa_handler = handler;
sigemptyset (&(action->sa_mask));
assert (sigaction (signum, action, NULL) == 0);
Additionally, send three of the same kind of signal to the parent in row and notice the functionality that produces.
Explanation / Answer
The code is as follows:
#include<iostream>
using namespace std;
#include<sys/types.h>
#include<unistd.h>
#include<string>
#include<stdlib.h>
#include <signal.h>
void sighandler(int sig)
{
if (sig == SIGUSR1)
{
cout << "SIGUSR1 received" << endl;
}
if (sig == SIGUSR2)
{
cout << "SIGUSR2 received" << endl;
}
if (sig == SIGUSR3)
{
cout << "SIGUSR3 received" << endl;
}
}
int main()
{
pid_t pid;
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = sighandler;
sigaction(SIGUSR1, &act, 0);
sigaction(SIGUSR2, &act, 0);
sigaction(SIGUSR3, &act, 0);
pid =fork();
if(pid==0) //child process
{
kill(getppid(),SIGUSR1);
usleep(1000);
kill(getppid(),SIGUSR2);
usleep(1000);
kill(getppid(),SIGUSR3);
}
else if(pid<0)
{
cout << "Error in fork()" << endl;
}
else // Parent Process
{
while (1)
{
usleep(100);
}
}
return 0;
}