2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 * @file single_instance.cpp
18 * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
20 * @brief This file is the implementation file of single instance
23 #include <dpl/single_instance.h>
24 #include <dpl/log/log.h>
28 #include <dpl/assert.h>
31 namespace // anonumous
33 const char *LOCK_PREFIX_PATH = "/tmp/dpl_single_instance_";
35 SingleInstance::SingleInstance() :
40 SingleInstance::~SingleInstance()
42 AssertMsg(!m_locked, "Single instance must be released before exit!");
45 bool SingleInstance::TryLock(const std::string &lockName)
47 LogPedantic("Locking single instance: " << lockName);
51 lock.l_type = F_WRLCK;
52 lock.l_whence = SEEK_SET;
58 TEMP_FAILURE_RETRY(open((std::string(LOCK_PREFIX_PATH) +
60 O_WRONLY | O_CREAT, 0666));
63 ThrowMsg(Exception::LockError, "Cannot open single instance lock file!");
67 int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock));
69 // Was the instance successfuly locked ?
71 LogPedantic("Instance locked: " << lockName);
80 if (errno == EACCES || errno == EAGAIN) {
81 LogPedantic("Instance is already running: " << lockName);
86 ThrowMsg(Exception::LockError, "Cannot lock single instance lock file!");
89 void SingleInstance::Release()
95 LogPedantic("Unlocking single instance");
100 lock.l_type = F_UNLCK;
101 lock.l_whence = SEEK_SET;
105 int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock));
107 // Was the instance successfuly unlocked ?
109 ThrowMsg(Exception::LockError,
110 "Cannot unlock single instance lock file!");
114 if (TEMP_FAILURE_RETRY(close(m_fdLock)) == -1) {
115 ThrowMsg(Exception::LockError,
116 "Cannot close single instance lock file!");
123 LogPedantic("Instance unlocked");