random_fork_test.cc 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #ifdef __unix__
  4. // Verifies that IDs don't clash after forking the process.
  5. //
  6. // See https://github.com/opentracing-contrib/nginx-opentracing/issues/52
  7. # include "src/common/random.h"
  8. # include <stdint.h>
  9. # include <sys/mman.h>
  10. # include <sys/wait.h>
  11. # include <unistd.h>
  12. # include <cstdlib>
  13. # include <iostream>
  14. using opentelemetry::sdk::common::Random;
  15. static uint64_t *child_id;
  16. int main()
  17. {
  18. // Set up shared memory to communicate between parent and child processes.
  19. //
  20. // See https://stackoverflow.com/a/13274800/4447365
  21. child_id = static_cast<uint64_t *>(
  22. mmap(nullptr, sizeof(*child_id), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0));
  23. *child_id = 0;
  24. if (fork() == 0)
  25. {
  26. *child_id = Random::GenerateRandom64();
  27. exit(EXIT_SUCCESS);
  28. }
  29. else
  30. {
  31. wait(nullptr);
  32. auto parent_id = Random::GenerateRandom64();
  33. auto child_id_copy = *child_id;
  34. munmap(static_cast<void *>(child_id), sizeof(*child_id));
  35. if (parent_id == child_id_copy)
  36. {
  37. std::cerr << "Child and parent ids are the same value " << parent_id << "\n";
  38. return -1;
  39. }
  40. }
  41. return 0;
  42. }
  43. #else
  44. int main()
  45. {
  46. return 0;
  47. }
  48. #endif