15 |
#include <fcntl.h> |
#include <fcntl.h> |
16 |
#include <stdlib.h> |
#include <stdlib.h> |
17 |
|
|
18 |
#include "util.h" |
#include "Util.h" |
19 |
|
|
20 |
#include "Exceptions.h" |
#include "Exceptions.h" |
21 |
|
|
38 |
{ |
{ |
39 |
bool error = false; |
bool error = false; |
40 |
lock(); |
lock(); |
41 |
std::string file = getSpoolFilename(); |
std::string file = findSpoolFilename(); |
42 |
std::ofstream out(file.c_str()); |
std::ofstream out(file.c_str()); |
43 |
if (out) { |
if (out) { |
44 |
out << recipient << "\n" << message; |
out << recipient << "\n" << message; |
50 |
|
|
51 |
if (error) |
if (error) |
52 |
throw std::runtime_error("Could not create spoolfile"); |
throw std::runtime_error("Could not create spoolfile"); |
53 |
|
this->filename = file; |
54 |
} |
} |
55 |
|
|
56 |
std::string Spooler::dequeue() |
std::string Spooler::dequeue() |
87 |
|
|
88 |
unlock(); |
unlock(); |
89 |
|
|
90 |
|
this->filename = file; |
91 |
|
|
92 |
if (file != "") |
if (file != "") |
93 |
return message; |
return message; |
94 |
else |
else |
95 |
throw filenotfoundexception(); |
throw filenotfoundexception(); |
96 |
} |
} |
97 |
|
|
98 |
std::string Spooler::getSpoolFilename() |
std::string Spooler::findSpoolFilename() |
99 |
{ |
{ |
100 |
std::string file; |
std::string file; |
101 |
std::stringstream ss; |
std::stringstream ss; |
116 |
::close(fd); |
::close(fd); |
117 |
return file; |
return file; |
118 |
} |
} |
119 |
|
int err = errno; |
120 |
|
::close(fd); |
121 |
|
|
122 |
if (errno == EEXIST) |
if (err == EEXIST) { |
123 |
continue; |
continue; |
124 |
|
} |
125 |
|
|
126 |
if (retrycount > 20) |
if (retrycount > 20) |
127 |
throw std::runtime_error("to many retry attempt at creating spool file"); |
throw std::runtime_error("to many retry attempt at creating spool file"); |
133 |
|
|
134 |
void Spooler::lock() |
void Spooler::lock() |
135 |
{ |
{ |
136 |
fd = open(spooldir.c_str() , O_RDONLY); |
lockfd = open(spooldir.c_str() , O_RDONLY); |
137 |
|
|
138 |
if (fd == -1) { |
if (lockfd == -1) { |
139 |
errnoException("Couldn open lockfile"); |
errnoException("Couldn open lockfile"); |
140 |
} |
} |
141 |
|
|
142 |
int status = flock(fd, LOCK_EX); |
int status = flock(lockfd, LOCK_EX); |
143 |
|
|
144 |
if (status == -1) { |
if (status == -1) { |
145 |
errnoException(); |
errnoException(); |
148 |
|
|
149 |
void Spooler::unlock() |
void Spooler::unlock() |
150 |
{ |
{ |
151 |
flock(fd, LOCK_UN); |
flock(lockfd, LOCK_UN); |
152 |
|
close(lockfd); |
153 |
|
} |
154 |
|
|
155 |
|
string Spooler::getFilename() |
156 |
|
{ |
157 |
|
return filename; |
158 |
} |
} |