Um schnell zu testen ob ein Rechner erreichbar ist, kann man ihn pingen. Der ping timeout dauert aber gern mal eine Sekunde. Wenn 10 Rechner nicht erreichbar sind, wartet man auch 10 Sekunden auf das Programm. Statt potentiell nur eine Sekunde. Die ping Anweisung kann man gut parallel ausführen. Zeit für std::async und std::future
Hier mein Beispiel, mit etwas Spielwiese:
#include <cstdlib> #include <iostream> #include <future> #include <thread> #include <string_view> auto status(std::string_view host) { auto command = "ping -W 1 -c 1 " + std::string(host) + " >/dev/null 2>&1"; return std::pair{std::system(command.c_str()), host}; } auto red() { return "\033[32m"; } auto green() { return "\033[31m"; } auto reset() { return "\033[0m"; } std::ostream& operator <<(std::ostream& s, const std::pair<int, std::string_view> p) { s << p.second << " "; if(p.first == 0) { s << red() << "UP " << reset(); } else { s << green() << "down " << reset(); } return s; } int main() { std::future f01 = std::async(std::launch::async, status, "rechner01"); std::future f02 = std::async(std::launch::async, status, "rechner02"); std::future f03 = std::async(std::launch::async, status, "rechner03"); // ... f01.wait(); f02.wait(); f03.wait(); // ... std::cout << f01.get() << f02.get() << f03.get() << "\n"; }