SubprocessTestParentDeathHelper.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright 2013-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. // This is a helper for the parentDeathSignal test in SubprocessTest.cpp.
  17. //
  18. // Basically, we create two processes, a parent and a child, and set the
  19. // child to receive SIGUSR1 when the parent exits. We set the child to
  20. // create a file when that happens. The child then kills the parent; the test
  21. // will verify that the file actually gets created, which means that everything
  22. // worked as intended.
  23. #include <fcntl.h>
  24. #include <signal.h>
  25. #include <sys/types.h>
  26. #include <glog/logging.h>
  27. #include <folly/Conv.h>
  28. #include <folly/Subprocess.h>
  29. #include <folly/portability/GFlags.h>
  30. #include <folly/portability/Unistd.h>
  31. using folly::Subprocess;
  32. DEFINE_bool(child, false, "");
  33. namespace {
  34. constexpr int kSignal = SIGUSR1;
  35. } // namespace
  36. void runChild(const char* file) {
  37. // Block SIGUSR1 so it's queued
  38. sigset_t sigs;
  39. CHECK_ERR(sigemptyset(&sigs));
  40. CHECK_ERR(sigaddset(&sigs, kSignal));
  41. CHECK_ERR(sigprocmask(SIG_BLOCK, &sigs, nullptr));
  42. // Kill the parent, wait for our signal.
  43. CHECK_ERR(kill(getppid(), SIGKILL));
  44. int sig = 0;
  45. CHECK_ERR(sigwait(&sigs, &sig));
  46. CHECK_EQ(sig, kSignal);
  47. // Signal completion by creating the file
  48. CHECK_ERR(creat(file, 0600));
  49. }
  50. [[noreturn]] void runParent(const char* file) {
  51. std::vector<std::string> args{"/proc/self/exe", "--child", file};
  52. Subprocess proc(args, Subprocess::Options().parentDeathSignal(kSignal));
  53. CHECK(proc.poll().running());
  54. // The child will kill us.
  55. for (;;) {
  56. pause();
  57. }
  58. }
  59. int main(int argc, char* argv[]) {
  60. gflags::ParseCommandLineFlags(&argc, &argv, true);
  61. CHECK_EQ(argc, 2);
  62. if (FLAGS_child) {
  63. runChild(argv[1]);
  64. } else {
  65. runParent(argv[1]);
  66. }
  67. return 0;
  68. }