• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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    u64 *leaf = stats.lookup(&key);
33    if (leaf) (*leaf)++;
34}
35
36void do_count(struct pt_regs *ctx) { stats_increment(S_COUNT); }
37""")
38b.attach_kprobe(event="sched_fork", fn_name="do_count")
39
40# stat indexes
41S_COUNT = c_int(1)
42
43# header
44print("Tracing... Ctrl-C to end.")
45
46# output
47while (1):
48    try:
49        sleep(1)
50    except KeyboardInterrupt:
51        exit()
52
53    print("%s: PIDs/sec: %d" % (strftime("%H:%M:%S"),
54        b["stats"][S_COUNT].value))
55    b["stats"].clear()
56