AzLearn

تمرين إعادة البناء

Parallel Pinger

أعد كتابة سكربت Bash يشغل فحص ping على عدة أهداف بالتوازي وينتظر النتائج.

bash ~14 دقيقة متوسط
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
#!/usr/bin/env bash
# Ping a list of targets in parallel, with a bounded batch size to avoid
# fork-bombing on large input lists. Portable to Bash 3.2+ (no `wait -n`).
set -euo pipefail

targets=(
	"localhost"
	"example.com"
	"learn.azizwares.sa"
)

ping_one() {
	local target="$1"

	if ping -c 1 -W 1 "$target" >/dev/null 2>&1; then
		printf '%-24s up\n' "$target"
	else
		printf '%-24s down\n' "$target"
	fi
}

batch=8
i=0
for target in "${targets[@]}"; do
	ping_one "$target" &
	i=$((i + 1))
	if ((i % batch == 0)); then
		wait
	fi
done

wait
اكتب هنا