Skip to content

Commit 55e9d93

Browse files
authored
Fixed PeriodicTaskExecutor fork handler (#1209) (#1213)
1 parent dea266b commit 55e9d93

2 files changed

Lines changed: 15 additions & 6 deletions

File tree

agent/native/libcommon/code/PeriodicTaskExecutor.h

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
namespace elasticapm::php {
1313

14-
1514
class PeriodicTaskExecutor : public ForkableInterface {
1615
private:
1716
auto getThreadWorkerFunction() {
@@ -30,7 +29,6 @@ class PeriodicTaskExecutor : public ForkableInterface {
3029

3130
~PeriodicTaskExecutor() {
3231
shutdown();
33-
3432
if (thread_.joinable()) {
3533
thread_.join();
3634
}
@@ -62,12 +60,17 @@ class PeriodicTaskExecutor : public ForkableInterface {
6260

6361
void prefork() final {
6462
shutdown();
65-
thread_.join();
63+
if (thread_.joinable()) {
64+
thread_.join();
65+
}
6666
}
6767

6868
void postfork([[maybe_unused]] bool child) final {
6969
working_ = true;
70+
71+
mutex_.lock();
7072
thread_ = std::thread(getThreadWorkerFunction());
73+
mutex_.unlock();
7174
pauseCondition_.notify_all();
7275
}
7376

@@ -107,8 +110,8 @@ class PeriodicTaskExecutor : public ForkableInterface {
107110
std::chrono::milliseconds sleepInterval_ = std::chrono::milliseconds(20);
108111
std::vector<task_t> periodicTasks_;
109112
worker_init_t workerInit_;
110-
std::thread thread_;
111113
std::mutex mutex_;
114+
std::thread thread_;
112115
std::condition_variable pauseCondition_;
113116
bool working_ = true;
114117
bool resumed_ = false;

agent/native/libcommon/test/PeriodicTaskExecutorTest.cpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,13 @@ TEST(PeriodicTaskExecutorTest, resumeAfterFork) {
4747

4848
periodicTaskExecutor_.setInterval(20ms);
4949

50-
pthread_atfork(fh_prepare, fh_parent, fh_child);
50+
51+
static bool pthread_atfork_called = false;
52+
53+
if (!pthread_atfork_called) {
54+
pthread_atfork(fh_prepare, fh_parent, fh_child);
55+
pthread_atfork_called = true;
56+
}
5157

5258
periodicTaskExecutor_.resumePeriodicTasks();
5359
std::this_thread::sleep_for(100ms);
@@ -60,7 +66,7 @@ TEST(PeriodicTaskExecutorTest, resumeAfterFork) {
6066

6167
ASSERT_GE(counter.load(), 13); // should be 15 in ideal world
6268
if (pid == 0) {
63-
exit(0);
69+
exit(testing::Test::HasFailure());
6470
}
6571
}
6672

0 commit comments

Comments
 (0)