blob: c4490043a59dfe395b663616d9bc5423018a545e [file] [log] [blame]
Brendan Greggebdb2422015-08-18 16:53:41 -07001#!/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) {
Brendan Greggb90bbab2016-02-15 15:55:08 -080032 u64 *leaf = stats.lookup(&key);
33 if (leaf) (*leaf)++;
34}
35
36void do_count(struct pt_regs *ctx) { stats_increment(S_COUNT); }
37""")
Brenden Blanco5eef65e2015-08-19 15:39:19 -070038b.attach_kprobe(event="sched_fork", fn_name="do_count")
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070039
40# stat indexes
Brendan Gregg94210542015-08-20 12:52:30 -070041S_COUNT = c_int(1)
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070042
43# header
Brendan Gregg762b1b42015-08-18 16:49:48 -070044print("Tracing... Ctrl-C to end.")
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070045
46# output
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070047while (1):
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080048 try:
49 sleep(1)
50 except KeyboardInterrupt:
51 exit()
Brendan Gregg48fbc3e2015-08-18 14:56:14 -070052
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080053 print("%s: PIDs/sec: %d" % (strftime("%H:%M:%S"),
54 b["stats"][S_COUNT].value))
55 b["stats"].clear()