运行使用Google Test Framework编写的死亡测试时,每个测试都会产生以下警告:

[WARNING] .../gtest-death-test.cc:789:: Death tests use fork(), which is unsafe
particularly in a threaded context. For this test, Google Test couldn't detect
the number of threads.

有没有办法让Google Test检测Linux上的线程数?

最佳答案

我查看了源代码,结果发现仅对MacOS X和QNX实现了线程数量检测,而在Linux或其他平台上则未实现。因此,我自己通过计算/proc/self/task中的条目数来实现缺少的功能。由于它可能对其他人有用,因此我将其发布在这里(我也将其发送到了Google Test group):

size_t GetThreadCount() {
  size_t thread_count = 0;
  if (DIR *dir = opendir("/proc/self/task")) {
    while (dirent *entry = readdir(dir)) {
      if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
        ++thread_count;
    }
    closedir(dir);
  }
  return thread_count;
}

截至2015年8月25日,Google测试implements GetThreadCount on Linux:
size_t GetThreadCount() {
  const string filename =
      (Message() << "/proc/" << getpid() << "/stat").GetString();
  return ReadProcFileField<int>(filename, 19);
}

10-07 19:30
查看更多