1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "rlz/lib/recursive_cross_process_lock_posix.h"
11 #include <sys/types.h>
14 #include "base/files/file_path.h"
15 #include "base/logging.h"
16 #include "base/posix/eintr_wrapper.h"
20 bool RecursiveCrossProcessLock::TryGetCrossProcessLock(
21 const base::FilePath
& lock_filename
) {
22 bool just_got_lock
= false;
24 // Emulate a recursive mutex with a non-recursive one.
25 if (pthread_mutex_trylock(&recursive_lock_
) == EBUSY
) {
26 if (pthread_equal(pthread_self(), locking_thread_
) == 0) {
27 // Some other thread has the lock, wait for it.
28 pthread_mutex_lock(&recursive_lock_
);
29 CHECK(locking_thread_
== 0);
36 locking_thread_
= pthread_self();
38 // Try to acquire file lock.
40 const int kMaxTimeoutMS
= 5000; // Matches Windows.
41 const int kSleepPerTryMS
= 200;
43 CHECK(file_lock_
== -1);
44 file_lock_
= open(lock_filename
.value().c_str(), O_RDWR
| O_CREAT
, 0666);
45 if (file_lock_
== -1) {
46 VPLOG(1) << "Failed to open: " << lock_filename
.value();
50 int flock_result
= -1;
52 while ((flock_result
=
53 HANDLE_EINTR(flock(file_lock_
, LOCK_EX
| LOCK_NB
))) == -1 &&
54 errno
== EWOULDBLOCK
&&
55 elapsed_ms
< kMaxTimeoutMS
) {
56 usleep(kSleepPerTryMS
* 1000);
57 elapsed_ms
+= kSleepPerTryMS
;
60 if (flock_result
== -1) {
61 VPLOG(1) << "Failed flock: " << lock_filename
.value();
68 return file_lock_
!= -1;
72 void RecursiveCrossProcessLock::ReleaseLock() {
73 if (file_lock_
!= -1) {
74 ignore_result(HANDLE_EINTR(flock(file_lock_
, LOCK_UN
)));
80 pthread_mutex_unlock(&recursive_lock_
);
83 } // namespace rlz_lib