Skip to content

Commit 0b85058

Browse files
committed
Revised code for changing from a boost named_mutex to using a boost file_lock which correctly unlocks on abnormal process termination.
1 parent e21ce1d commit 0b85058

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

DeepSkyStacker/DeepSkyStacker.cpp

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,12 @@
3737
//
3838
#include <stdafx.h>
3939
#include <htmlhelp.h>
40-
#include <boost/interprocess/sync/named_mutex.hpp>
40+
#include <boost/interprocess/sync/file_lock.hpp>
41+
#include <boost/interprocess/sync/scoped_lock.hpp>
4142
#include <boost/interprocess/exceptions.hpp>
4243

44+
#include <fstream>
45+
4346
namespace bip = boost::interprocess;
4447

4548
#include "DeepSkyStacker.h"
@@ -1135,9 +1138,31 @@ int main(int argc, char* argv[])
11351138
DeepSkyStacker mainWindow;
11361139

11371140
ZTRACE_RUNTIME("Checking Mutex");
1138-
bip::named_mutex dssMutex{ bip::open_or_create, "DeepSkyStacker.Mutex.UniqueID.12354687" };
1139-
bip::scoped_lock<bip::named_mutex> lk(dssMutex, bip::defer_lock);
1140-
const bool firstInstance{ lk.try_lock() };
1141+
//
1142+
// Get the name of the writable local applicaiton data directory
1143+
// and create the directories if necessary
1144+
//
1145+
1146+
QString mutexFileName{ QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) };
1147+
fs::path file{ mutexFileName.toStdU16String() };
1148+
create_directories(file);
1149+
1150+
//
1151+
// Append the file name to the directory name
1152+
//
1153+
mutexFileName += "/DeepSkyStacker.Interprocess.Mutex";
1154+
1155+
//
1156+
// Create the file it doesn't exist. It is intentionally never deleted.
1157+
//
1158+
auto newFile = std::ofstream(mutexFileName.toUtf8().constData());
1159+
1160+
//
1161+
// Use a boost::interprocess::file_lock as unlike a named_mutex, the OS removes the lock in the case of abnormal termination
1162+
//
1163+
bip::file_lock dssMutex{ mutexFileName.toUtf8().constData() };
1164+
bip::scoped_lock<bip::file_lock> lock(dssMutex, bip::try_to_lock);
1165+
const bool firstInstance{ lock.owns() };
11411166
ZTRACE_RUNTIME(" firstInstance: %s", firstInstance ? "true" : "false");
11421167

11431168
if (firstInstance)

0 commit comments

Comments
 (0)