2 * Copyright 2016 Facebook, Inc.
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 #include <folly/File.h>
19 #include <boost/thread/locks.hpp>
21 #include <folly/String.h>
22 #include <folly/Subprocess.h>
23 #include <folly/experimental/io/FsUtil.h>
24 #include <folly/experimental/TestUtil.h>
26 #include <gflags/gflags.h>
27 #include <glog/logging.h>
28 #include <gtest/gtest.h>
32 using namespace folly;
33 using namespace folly::test;
35 DEFINE_bool(s, false, "get shared lock");
36 DEFINE_bool(x, false, "get exclusive lock");
39 typedef std::unique_lock<File> Lock;
40 typedef boost::shared_lock<File> SharedLock;
42 // Find out where we are.
43 static constexpr size_t pathLength = 2048;
44 char buf[pathLength + 1];
45 int r = readlink("/proc/self/exe", buf, pathLength);
50 auto helper_basename = "file_test_lock_helper";
52 if (fs::exists(me.parent_path() / helper_basename)) {
53 helper = me.parent_path() / helper_basename;
55 throw std::runtime_error(
56 folly::to<std::string>("cannot find helper ", helper_basename));
59 TemporaryFile tempFile;
60 File f(tempFile.fd());
62 enum LockMode { EXCLUSIVE, SHARED };
63 auto testLock = [&](LockMode mode, bool expectedSuccess) {
64 auto ret = Subprocess({helper.native(),
65 mode == SHARED ? "-s" : "-x",
66 tempFile.path().native()}).wait();
67 EXPECT_TRUE(ret.exited());
69 EXPECT_EQ(expectedSuccess ? 0 : 42, ret.exitStatus());
73 // Make sure nothing breaks and things compile.
76 { SharedLock lock(f); }
79 Lock lock(f, std::defer_lock);
80 EXPECT_TRUE(lock.try_lock());
84 SharedLock lock(f, boost::defer_lock);
85 EXPECT_TRUE(lock.try_lock());
91 testLock(EXCLUSIVE, false);
97 testLock(SHARED, false);
103 testLock(EXCLUSIVE, false);
106 // S does not block S
109 testLock(SHARED, true);