-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalarm.cpp
82 lines (73 loc) · 1.63 KB
/
alarm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "header.h"
int p[2];
extern vector<int> vectalarm;
extern vector<pair<time_t,string>> allalarm;
//When enter into shell check all alarms from alarm.txt
//if alarm time < current time
// alarm is missed so print appropiate message
//else
// set alarm for this shell
void checkMissedAlarms()
{
ifstream infile("alarm.txt");
for(string line;getline( infile, line);)
{
time_t timestamp = stoll(line.substr(0,line.find(":")));
string msg = line.substr(line.find(":")+1);
if(time((time_t *)0)>timestamp)
{
cout<<"Missed Alarm "<<timestamp <<" : "<<msg<<endl;
continue;
}
else
{
checkAlarm(timestamp,msg);
}
}
infile.close();
}
//create a child process for each alarm
void checkAlarm(time_t alarmtime,string msg)
{
int child=fork();
vectalarm.push_back(child);
if(child==0)
{
while(time((time_t *)0)!=alarmtime){
}
cout<<"Alarm : "<<msg<<"\n";
exit(1);
}
}
void alarmHandler(int x,string msg)
{
time_t curtime = time((time_t*)0);
time_t alarmtime = curtime + x;
cout<<"Alarm set : "<<curtime<<":"<<alarmtime<<" : "<<msg<<endl<<endl;
allalarm.push_back(make_pair(alarmtime,msg));
checkAlarm(alarmtime,msg);
return;
}
//when exit from shell store each alarm in text file
void alarmExit()
{
for(int i=0;i<vectalarm.size();i++)
{
kill(vectalarm[i],SIGKILL);
}
int fd = open("alarm.txt",O_WRONLY | O_TRUNC | O_CREAT,0644);
if(fd==-1)
{
cout<<"Not able to open alarm file";
return;
}
for(auto alm : allalarm)
{
if(alm.first > time((time_t *)0))
{
string alarm_record = to_string(alm.first)+":"+alm.second+"\n";
write(fd,alarm_record.c_str(),alarm_record.size());
}
}
close(fd);
}