|
| 1 | +// Copyright 2025 The TensorStore Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#if !defined(_WIN32) && !defined(__APPLE__) && defined(__has_include) |
| 16 | +#if __has_include(<pthread.h>) |
| 17 | +#define TENSORSTORE_INTERNAL_ENABLE_FORK_TEST 1 |
| 18 | +// In order to run the death test, both pthreads and fork are required, |
| 19 | +// and the test must be run in gunit's thread-safe mode. |
| 20 | +#endif |
| 21 | +#endif |
| 22 | + |
| 23 | +#if defined(TENSORSTORE_INTERNAL_ENABLE_FORK_TEST) |
| 24 | + |
| 25 | +#include <pthread.h> |
| 26 | +#include <unistd.h> |
| 27 | + |
| 28 | +#include <gtest/gtest.h> |
| 29 | +#include "tensorstore/internal/thread/thread.h" |
| 30 | + |
| 31 | +namespace { |
| 32 | + |
| 33 | +TEST(ThreadDeathTest, Fork) { |
| 34 | + GTEST_FLAG_SET(death_test_style, "threadsafe"); |
| 35 | + // Span a thread and join it; this should register pthread_at_fork() |
| 36 | + // handler which will crash if fork() is called. |
| 37 | + int x = 0; |
| 38 | + tensorstore::internal::Thread my_thread({}, [&x]() { x = 1; }); |
| 39 | + my_thread.Join(); |
| 40 | + EXPECT_EQ(1, x); |
| 41 | + |
| 42 | + // fork()-ing after starting a thread is not supported; forcibly crash. |
| 43 | + EXPECT_DEATH(fork(), ""); |
| 44 | +} |
| 45 | + |
| 46 | +} // namespace |
| 47 | + |
| 48 | +#endif // TENSORSTORE_INTERNAL_ENABLE_FORK_TEST |
0 commit comments