libbpf 开发指南:将 eBPF 程序固定到一个给定的文件系统路径

目录

函数原型与解释

代码demo

makefile

cmake

期望输出


函数原型与解释

LIBBPF_API int bpf_program__pin(struct bpf_program *prog, const char *path);

参数说明:

  • prog:一个指向 bpf_program 结构的指针,表示要固定的 eBPF 程序。
  • path:一个字符串,表示将 eBPF 程序固定到的文件系统路径。

返回值:一个整数。正常情况下返回 0;如果发生错误,返回负数。

代码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;

    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;
    }

    if (bpf_program__pin(prog, pin_path)) {
        fprintf(stderr, "Error pinning BPF program: %s\n", strerror(errno));
        return 1;
    }

    printf("BPF program pinned at: %s\n", pin_path);

    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 program pinned at: /sys/fs/bpf/my_bpf_prog

在这个例子中,eBPF 程序被固定在 /sys/fs/bpf/my_bpf_prog 路径。要查看已固定的程序,可以使用以下命令:

sudo bpftool prog show pinned /sys/fs/bpf/my_bpf_prog

请注意,在运行示例时,需要具有适当的权限,因此使用 sudo 运行它。另外,确保 /sys/fs/bpf 目录存在。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ym影子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值