CTest CDash run only once

This CMake function works across Windows, macOS, and Linux checks that the current CTest script is the only instance of CTest running at the time. We use this in CTest CDash scripts to avoid unexpectedly long-running scripts overlapping with the next day’s runs. That could exhaust memory and crash the computer.

function(ctest_once_only)
# check if CTest already running, error if so
if(WIN32)
find_program(tasklist NAMES tasklist REQUIRED)
execute_process(COMMAND ${tasklist} /fi "Imagename eq ctest.exe" /fo csv
TIMEOUT 10
RESULT_VARIABLE ret
OUTPUT_VARIABLE out
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(NOT ret EQUAL 0)
message(FATAL_ERROR "Could not check if CTest already running")
endif()
string(REGEX MATCHALL "(ctest.exe)" mat "${out}")
list(LENGTH mat L)
if(NOT L EQUAL 1)
message(FATAL_ERROR "CTest already running ${L} times, not starting again.
${mat}")
endif()
else()
find_program(pgrep NAMES pgrep REQUIRED)
execute_process(COMMAND ${pgrep} ctest
TIMEOUT 10
RESULT_VARIABLE ret
OUTPUT_VARIABLE out
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(ret EQUAL 1)
message(VERBOSE "No CTest found running, proceeding.")
return()
elseif(NOT ret EQUAL 0)
message(FATAL_ERROR "Could not check if CTest already running")
endif()
string(REGEX MATCHALL "([0-9]+)" mat "${out}")
list(LENGTH mat L)
if(NOT L EQUAL 1)
message(FATAL_ERROR "CTest already running ${L} times, not starting again.
${mat}")
endif()
endif()
endfunction(ctest_once_only)