1#!/usr/bin/env python 2# 3# This is a Hello World example that uses BPF_PERF_OUTPUT. 4 5from bcc import BPF 6import ctypes as ct 7 8# define BPF program 9prog = """ 10#include <linux/sched.h> 11 12// define output data structure in C 13struct data_t { 14 u32 pid; 15 u64 ts; 16 char comm[TASK_COMM_LEN]; 17}; 18BPF_PERF_OUTPUT(events); 19 20int hello(struct pt_regs *ctx) { 21 struct data_t data = {}; 22 23 data.pid = bpf_get_current_pid_tgid(); 24 data.ts = bpf_ktime_get_ns(); 25 bpf_get_current_comm(&data.comm, sizeof(data.comm)); 26 27 events.perf_submit(ctx, &data, sizeof(data)); 28 29 return 0; 30} 31""" 32 33# load BPF program 34b = BPF(text=prog) 35b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="hello") 36 37# define output data structure in Python 38TASK_COMM_LEN = 16 # linux/sched.h 39class Data(ct.Structure): 40 _fields_ = [("pid", ct.c_uint), 41 ("ts", ct.c_ulonglong), 42 ("comm", ct.c_char * TASK_COMM_LEN)] 43 44# header 45print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "MESSAGE")) 46 47# process event 48start = 0 49def print_event(cpu, data, size): 50 global start 51 event = ct.cast(data, ct.POINTER(Data)).contents 52 if start == 0: 53 start = event.ts 54 time_s = (float(event.ts - start)) / 1000000000 55 print("%-18.9f %-16s %-6d %s" % (time_s, event.comm, event.pid, 56 "Hello, perf_output!")) 57 58# loop with callback to print_event 59b["events"].open_perf_buffer(print_event) 60while 1: 61 b.perf_buffer_poll() 62