File: pidpersec.py

package info (click to toggle)
bpfcc 0.18.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 12,368 kB
  • sloc: ansic: 132,727; python: 36,226; cpp: 26,973; sh: 710; yacc: 525; makefile: 141; lex: 94
file content (55 lines) | stat: -rwxr-xr-x 1,137 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# pidpersec Count new processes (via fork).
#           For Linux, uses BCC, eBPF. See .c file.
#
# USAGE: pidpersec
#
# Written as a basic example of counting an event.
#
# Copyright (c) 2015 Brendan Gregg.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 11-Aug-2015   Brendan Gregg   Created this.

from bcc import BPF
from ctypes import c_int
from time import sleep, strftime

# load BPF program
b = BPF(text="""
#include <uapi/linux/ptrace.h>

enum stat_types {
    S_COUNT = 1,
    S_MAXSTAT
};

BPF_ARRAY(stats, u64, S_MAXSTAT);

static void stats_increment(int key) {
    u64 *leaf = stats.lookup(&key);
    if (leaf) (*leaf)++;
}

void do_count(struct pt_regs *ctx) { stats_increment(S_COUNT); }
""")
b.attach_kprobe(event="sched_fork", fn_name="do_count")

# stat indexes
S_COUNT = c_int(1)

# header
print("Tracing... Ctrl-C to end.")

# output
while (1):
    try:
        sleep(1)
    except KeyboardInterrupt:
        exit()

    print("%s: PIDs/sec: %d" % (strftime("%H:%M:%S"),
        b["stats"][S_COUNT].value))
    b["stats"].clear()