1#!/usr/bin/env python 2# @lint-avoid-python-3-compatibility-imports 3# 4# pidpersec Count new processes (via fork). 5# For Linux, uses BCC, eBPF. See .c file. 6# 7# USAGE: pidpersec 8# 9# Written as a basic example of counting an event. 10# 11# Copyright (c) 2015 Brendan Gregg. 12# Licensed under the Apache License, Version 2.0 (the "License") 13# 14# 11-Aug-2015 Brendan Gregg Created this. 15 16from bcc import BPF 17from ctypes import c_int 18from time import sleep, strftime 19 20# load BPF program 21b = BPF(text=""" 22#include <uapi/linux/ptrace.h> 23 24enum stat_types { 25 S_COUNT = 1, 26 S_MAXSTAT 27}; 28 29BPF_ARRAY(stats, u64, S_MAXSTAT); 30 31static void stats_increment(int key) { 32 stats.atomic_increment(key); 33} 34 35void do_count(struct pt_regs *ctx) { stats_increment(S_COUNT); } 36""") 37b.attach_kprobe(event="sched_fork", fn_name="do_count") 38 39# stat indexes 40S_COUNT = c_int(1) 41 42# header 43print("Tracing... Ctrl-C to end.") 44 45# output 46while (1): 47 try: 48 sleep(1) 49 except KeyboardInterrupt: 50 exit() 51 52 print("%s: PIDs/sec: %d" % (strftime("%H:%M:%S"), 53 b["stats"][S_COUNT].value)) 54 b["stats"].clear() 55