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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| [root@ningan ebpf]
// 包含头文件
// 定义数据结构 struct data_t { u32 pid; u64 ts; char comm[TASK_COMM_LEN]; char fname[NAME_MAX]; };
// 定义性能事件映射 BPF_PERF_OUTPUT(events);
// 定义kprobe处理函数 int hello_world(struct pt_regs *ctx, int dfd, const char __user * filename, struct open_how *how) { struct data_t data = { };
// 获取PID和时间 data.pid = bpf_get_current_pid_tgid(); data.ts = bpf_ktime_get_ns();
// 获取进程名 if (bpf_get_current_comm(&data.comm, sizeof(data.comm)) == 0) { bpf_probe_read(&data.fname, sizeof(data.fname), (void *)filename); }
// 提交性能事件 events.perf_submit(ctx, &data, sizeof(data)); return 0; }
[root@ningan ebpf]
from bcc import BPF
b = BPF(src_file="trace-open.c") b.attach_kprobe(event="do_sys_openat2", fn_name="hello_world")
print("%-18s %-16s %-6s %-16s" % ("TIME(s)", "COMM", "PID", "FILE"))
start = 0 def print_event(cpu, data, size): global start event = b["events"].event(data) if start == 0: start = event.ts time_s = (float(event.ts - start)) / 1000000000 print("%-18.9f %-16s %-6d %-16s" % (time_s, event.comm, event.pid, event.fname))
b["events"].open_perf_buffer(print_event) while 1: try: b.perf_buffer_poll() except KeyboardInterrupt: exit()
|