Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / rlz / lib / recursive_cross_process_lock_posix.cc
blob965bd9acdd4e0f97bf145c2f9f8b7cebedc317fd
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"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sys/file.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.h>
14 #include "base/files/file_path.h"
15 #include "base/logging.h"
16 #include "base/posix/eintr_wrapper.h"
18 namespace rlz_lib {
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);
30 just_got_lock = true;
32 } else {
33 just_got_lock = true;
36 locking_thread_ = pthread_self();
38 // Try to acquire file lock.
39 if (just_got_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();
47 return false;
50 int flock_result = -1;
51 int elapsed_ms = 0;
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();
62 close(file_lock_);
63 file_lock_ = -1;
64 return false;
66 return true;
67 } else {
68 return file_lock_ != -1;
72 void RecursiveCrossProcessLock::ReleaseLock() {
73 if (file_lock_ != -1) {
74 ignore_result(HANDLE_EINTR(flock(file_lock_, LOCK_UN)));
75 close(file_lock_);
76 file_lock_ = -1;
79 locking_thread_ = 0;
80 pthread_mutex_unlock(&recursive_lock_);
83 } // namespace rlz_lib