import json
import os
import sys
import time
from denet import execute_with_monitoring
def run_stress_test():
print(f"Parent process: {os.getpid()}")
for i in range(4):
pid = os.fork()
if pid == 0: print(f"Child process {i + 1}: {os.getpid()}")
start_time = time.time()
while time.time() - start_time < 2:
_ = [i * i * i for i in range(100000)]
sys.exit(0)
print("Parent waiting for children to complete...")
for _ in range(4):
os.wait()
print("All child processes completed!")
return 0
def main():
print("Starting child process monitoring example...")
exit_code, monitor = execute_with_monitoring(
cmd=[
sys.executable,
"-c",
"import os, sys, time; "
"print(f'Parent: {os.getpid()}'); "
"for i in range(4): "
" pid = os.fork(); "
" if pid == 0: " " print(f'Child {i+1}: {os.getpid()}'); "
" start = time.time(); "
" while time.time() - start < 3: " " _ = [i*i*i for i in range(50000)]; " " sys.exit(0); "
"for _ in range(4): os.wait(); "
"print('All children completed');",
],
base_interval_ms=100, max_interval_ms=500, store_in_memory=True, output_file="stress_monitor.jsonl", include_children=True, )
samples = monitor.get_samples()
summary_json = monitor.get_summary()
summary = json.loads(summary_json)
print("\n===== Monitoring Results =====")
print(f"Total samples collected: {len(samples)}")
print(f"Average CPU usage: {summary['avg_cpu_usage']:.2f}%")
print(f"Peak memory usage: {summary['peak_mem_rss_kb'] / 1024:.2f} MB")
print(f"Maximum processes monitored: {summary['max_processes']}")
process_counts = []
for sample in samples:
if isinstance(sample, str):
sample = json.loads(sample)
if "aggregated" in sample:
count = sample["aggregated"].get("process_count", 1)
process_counts.append(count)
elif "process_count" in sample:
process_counts.append(sample["process_count"])
if process_counts:
print("\nProcess count over time:")
for i, count in enumerate(process_counts):
print(f"Sample {i + 1}: {count} processes")
print("\nExample complete. Results written to stress_monitor.jsonl")
return exit_code
if __name__ == "__main__":
sys.exit(main())