proxygen
AtForkTest.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017-present Facebook, Inc.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 #include <folly/detail/AtFork.h>
17 
19 #include <glog/logging.h>
20 
21 #include <atomic>
22 #include <mutex>
23 #include <thread>
24 
25 TEST(ThreadLocal, AtFork) {
26  int foo;
27  bool forked = false;
29  &foo,
30  [&] {
31  forked = true;
32  return true;
33  },
34  [] {},
35  [] {});
36  auto pid = fork();
37  if (pid) {
38  int status;
39  auto pid2 = wait(&status);
40  EXPECT_EQ(status, 0);
41  EXPECT_EQ(pid, pid2);
42  } else {
43  exit(0);
44  }
45  EXPECT_TRUE(forked);
46  forked = false;
48  pid = fork();
49  if (pid) {
50  int status;
51  auto pid2 = wait(&status);
52  EXPECT_EQ(status, 0);
53  EXPECT_EQ(pid, pid2);
54  } else {
55  exit(0);
56  }
57  EXPECT_FALSE(forked);
58 }
59 
60 TEST(ThreadLocal, AtForkOrdering) {
61  std::atomic<bool> done{false};
62  std::atomic<bool> started{false};
63  std::mutex a;
64  std::mutex b;
65  int foo;
66  int foo2;
68  &foo,
69  [&] { return a.try_lock(); },
70  [&] { a.unlock(); },
71  [&] { a.unlock(); });
73  &foo2,
74  [&] { return b.try_lock(); },
75  [&] { b.unlock(); },
76  [&] { b.unlock(); });
77 
78  auto thr = std::thread([&]() {
79  std::lock_guard<std::mutex> g(a);
80  started = true;
81  usleep(100);
82  std::lock_guard<std::mutex> g2(b);
83  });
84  while (!started) {
85  }
86  auto pid = fork();
87  if (pid) {
88  int status;
89  auto pid2 = wait(&status);
90  EXPECT_EQ(status, 0);
91  EXPECT_EQ(pid, pid2);
92  } else {
93  exit(0);
94  }
95  done = true;
96  thr.join();
97 }
char b
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
FOLLY_NOINLINE void foo2()
bool wait(Waiter *waiter, bool shouldSleep, Waiter *&next)
char a
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
std::mutex mutex
g_t g(f_t)
TEST(ThreadLocal, AtFork)
Definition: AtForkTest.cpp:25
static void unregisterHandler(void *object)
Definition: AtFork.cpp:118
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
static void registerHandler(void *object, folly::Function< bool()> prepare, folly::Function< void()> parent, folly::Function< void()> child)
Definition: AtFork.cpp:108