107 lines
2.1 KiB
C++
107 lines
2.1 KiB
C++
#include<stdio.h>
|
|
#include <sys/types.h>
|
|
#include <signal.h>
|
|
#include <unistd.h>
|
|
#include <iostream>
|
|
#include <cstdlib>
|
|
using namespace std;
|
|
|
|
//this function prints a message and changes the function to handle the SIGINT command to kill_func()
|
|
void myFunction(int sigVal);
|
|
|
|
// handles after alarm alarm
|
|
void alarmFunction(int ignore);
|
|
int child;
|
|
|
|
// handles SIG_INT while the alarm is active
|
|
void ignoreFunc(int ignore);
|
|
//This function kills the process that makes a call to this function
|
|
void kill_func(int killSignal);
|
|
|
|
// handles killing the child
|
|
void childKillFunc(int kill);
|
|
|
|
int main()
|
|
{
|
|
child = fork();
|
|
// ignore the SIGINT signal
|
|
// .. SIGINT is ctrl+c
|
|
// .. ignoreFunc is the user-defined signal handler
|
|
//
|
|
signal(SIGINT,ignoreFunc);
|
|
// for alarm signal, call function alarmFunction()
|
|
// .. means when alarm goes off, alarmFunction will be called
|
|
|
|
signal(SIGALRM,alarmFunction);
|
|
//set alarm for 15 seconds from now
|
|
alarm(10);
|
|
//printf("This gets printed as soon as alarm is called\n");
|
|
// just running infinitely
|
|
while(1);
|
|
}
|
|
|
|
void myFunction(int sigVal)
|
|
{
|
|
printf("Received signal %d\n", sigVal);
|
|
printf("Now you can kill me..\n");
|
|
signal(SIGINT,kill_func);
|
|
}
|
|
|
|
void alarmFunction(int ignore)
|
|
{
|
|
if (child== 0)
|
|
{
|
|
//define user signal and kill(child, USRSIG1) to send signal to child
|
|
|
|
signal(SIGINT,SIG_IGN);
|
|
signal(SIGUSR1, childKillFunc);
|
|
}
|
|
else
|
|
{
|
|
printf("Received signal %d\n", ignore);
|
|
printf("Now you can kill me..\n");
|
|
signal(SIGINT,kill_func);
|
|
}
|
|
}
|
|
|
|
void kill_func(int killSignal)
|
|
{
|
|
if(child == 0)
|
|
{
|
|
|
|
}
|
|
else
|
|
{
|
|
//define user signal and kill(child, USRSIG1) to send signal to child
|
|
|
|
printf("Sending signal to child\n");
|
|
kill(child, SIGUSR1);
|
|
printf("Received kill signal %d\n",killSignal);
|
|
printf("\tDying process %d\n",getpid());
|
|
exit(0);
|
|
}
|
|
|
|
}
|
|
|
|
void childKillFunc(int kill)
|
|
{
|
|
if (child == 0)
|
|
{
|
|
cout << "Received kill signal" << endl;
|
|
cout << "Child Process " << getpid() << " is dying" << endl;
|
|
exit(0);
|
|
}
|
|
|
|
}
|
|
|
|
void ignoreFunc(int ignore)
|
|
{
|
|
|
|
if(child == 0)
|
|
{
|
|
}
|
|
else
|
|
{
|
|
cout << "Can't kill processes now\n";
|
|
}
|
|
} |