Skip to content

Commit 1af48a5

Browse files
committed
Auto create pid file and safe current running pid for service
1 parent 5eca09b commit 1af48a5

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

source/unixservice/main.cpp

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -105,16 +105,23 @@ int main() {
105105

106106
std::ifstream fileCheck( pidfile );
107107
/* Try to lock file - or even check if its available on c++ */
108-
if ( fileCheck.good() ) {
108+
if ( !fileCheck.good() ) {
109109

110110
/* Couldn't get lock on lock file */
111111
/* NOTE: In c++ it is not (yet) possible to lock a file */
112-
// syslog(LOG_INFO, "Could not lock PID lock file %s, exiting", pidfile.c_str());
113-
// exit(EXIT_FAILURE);
112+
std::ofstream fileCreate;
113+
fileCreate.open( pidfile );
114+
if ( !fileCreate.is_open() ) {
115+
116+
/* Couldn't create lock file */
117+
syslog( LOG_INFO, "Could not create PID lock file %s, exiting", pidfile.c_str() );
118+
exit( EXIT_FAILURE );
119+
}
120+
fileCreate.close();
114121
}
115122

116-
std::fstream file;
117-
file.open( pidfile );
123+
std::ofstream file;
124+
file.open( pidfile, std::ofstream::out | std::ofstream::in );
118125
if ( !file.is_open() ) {
119126

120127
/* Couldn't open lock file */
@@ -129,7 +136,7 @@ int main() {
129136

130137
/* Get and format PID */
131138
std::string str = std::to_string( getpid() );
132-
if ( !currentPid.empty() && currentPid == str ) {
139+
if ( !currentPid.empty() && currentPid != str ) {
133140

134141
/* Couldn't open lock file */
135142
syslog( LOG_INFO, "Service allready running as PID %s, exiting", currentPid.c_str() );
@@ -138,6 +145,7 @@ int main() {
138145

139146
/* write pid to lockfile */
140147
file << str;
148+
file.close();
141149
// DAEMONIZE END
142150

143151
// SERVICE START
@@ -150,9 +158,6 @@ int main() {
150158
syslog( LOG_NOTICE, "Stopping %s", DAEMON_NAME );
151159
closelog();
152160

153-
/* Close pid information file */
154-
file.close();
155-
156161
/* Remove content of file */
157162
std::ofstream ofs;
158163
ofs.open( pidfile, std::ofstream::out | std::ofstream::trunc );

0 commit comments

Comments
 (0)