目录
函数原型与解释
LIBBPF_API struct bpf_link * bpf_link__open(const char *path);
参数说明:
- path:一个字符串,表示已固定 eBPF 程序的文件系统路径。
返回值:一个指向 bpf_link 结构的指针,表示 eBPF 程序的链接。如果打开链接失败,将返回 NULL。
代码demo
#include <linux/bpf.h> #include <bpf/bpf_helpers.h> SEC("kprobe/__x64_sys_getpid") int bpf_prog1(struct pt_regs *ctx) { bpf_printk("sys_getpid called\n"); return 0; } char _license[] SEC("license") = "GPL";
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <linux/bpf.h> #include <bpf/bpf.h> #include <bpf/libbpf.h> int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "Usage: %s <bpf_program.o> <pin_path>\n", argv[0]); return 1; } const char *bpf_program_path = argv[1]; const char *pin_path = argv[2]; struct bpf_object *obj = NULL; struct bpf_program *prog = NULL; struct bpf_link *link = NULL; if (bpf_prog_load(bpf_program_path, BPF_PROG_TYPE_KPROBE, &obj, &prog)) { fprintf(stderr, "Error loading BPF program: %s\n", strerror(errno)); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "Error attaching BPF program: %s\n", strerror(errno)); return 1; } if (bpf_link__pin(link, pin_path)) { fprintf(stderr, "Error pinning BPF link: %s\n", strerror(errno)); return 1; } printf("BPF link pinned at: %s\n", pin_path); // Wait for user input to unpin and close printf("Press Enter to unpin and close the BPF link...\n"); getchar(); struct bpf_link *opened_link = bpf_link__open(pin_path); if (opened_link == NULL) { fprintf(stderr, "Error opening pinned BPF link: %s\n", strerror(errno)); return 1; } bpf_link__unpin(opened_link, pin_path); printf("BPF link unpinned from: %s\n", pin_path); bpf_link__disconnect(opened_link); bpf_link__destroy(opened_link); bpf_link__destroy(link); bpf_object__unload(obj); return 0; }
makefile
CC=gcc CFLAGS=-I/usr/include/bpf -I./include LDFLAGS=-lbpf all: test test: test.c $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) clean: rm -f test
cmake
cmake_minimum_required(VERSION 2.8) project(test) set(CMAKE_C_FLAGS "-I/usr/include/bpf -I./include") add_executable(test test.c) target_link_libraries(test bpf)
期望输出
make
./demo
BPF link pinned at: /sys/fs/bpf/my_bpf_link Press Enter to unpin and close the BPF link... BPF link unpinned from: /sys/fs/bpf/my_bpf_link