blob: be72443534bf27ef7bad2f2b26adb9e3fcca9c9a [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08002# @lint-avoid-python-3-compatibility-imports
Brendan Gregg48fbc3e2015-08-18 14:56:14 -07003#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08004# pidpersec Count new processes (via fork).
5# For Linux, uses BCC, eBPF. See .c file.
Brendan Gregg48fbc3e2015-08-18 14:56:14 -07006#
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#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080014# 11-Aug-2015 Brendan Gregg Created this.
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070015
Brenden Blancoc35989d2015-09-02 18:04:07 -070016from bcc import BPF
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080017from ctypes import c_int
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070018from time import sleep, strftime
19
20# load BPF program
Brendan Greggb90bbab2016-02-15 15:55:08 -080021b = BPF(text="""
22#include <uapi/linux/ptrace.h>
23
24enum stat_types {
25 S_COUNT = 1,
26 S_MAXSTAT
27};
28
Brenden Blancod51870b2017-08-16 11:29:23 -070029BPF_ARRAY(stats, u64, S_MAXSTAT);
Brendan Greggb90bbab2016-02-15 15:55:08 -080030
Brenden Blanco3f28e7b2017-04-20 09:33:44 -070031static void stats_increment(int key) {
zcy80242fb2021-07-02 00:12:32 +080032 stats.atomic_increment(key);
Brendan Greggb90bbab2016-02-15 15:55:08 -080033}
34
35void do_count(struct pt_regs *ctx) { stats_increment(S_COUNT); }
36""")
Brenden Blanco5eef65e2015-08-19 15:39:19 -070037b.attach_kprobe(event="sched_fork", fn_name="do_count")
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070038
39# stat indexes
Brendan Gregg94210542015-08-20 12:52:30 -070040S_COUNT = c_int(1)
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070041
42# header
Brendan Gregg762b1b42015-08-18 16:49:48 -070043print("Tracing... Ctrl-C to end.")
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070044
45# output
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070046while (1):
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080047 try:
48 sleep(1)
49 except KeyboardInterrupt:
50 exit()
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070051
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080052 print("%s: PIDs/sec: %d" % (strftime("%H:%M:%S"),
53 b["stats"][S_COUNT].value))
54 b["stats"].clear()