libbpf Development Guide: Get the file descriptor associated with the given eBPF link

Table of contents

Function prototypes and explanations

Code demo

makefile

cmake

expected output


Function prototypes and explanations

LIBBPF_API int bpf_link__fd(const struct bpf_link *link);

Parameter Description:

  • link: A pointer to a bpf_link structure, indicating the eBPF link to be operated on.

Return value: An integer representing the file descriptor associated with the given eBPF link. If an error occurs, a negative number will be returned.

Code 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 != 2) {
        fprintf(stderr, "Usage: %s <bpf_program.o>\n", argv[0]);
        return 1;
    }

    const char *bpf_program_path = argv[1];
    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;
    }

    int fd = bpf_link__fd(link);
    if (fd < 0) {
        fprintf(stderr, "Error getting BPF link file descriptor: %s\n", strerror(errno));
        return 1;
    }

    printf("BPF link file descriptor: %d\n", fd);

    // Wait for user input to disconnect and destroy the link
    printf("Press Enter to disconnect and destroy the BPF link...\n");
    getchar();

    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)

expected output

make

./demo

BPF link file descriptor:3
Press Enter to disconnect and destroy the BPF link...

おすすめ

転載: blog.csdn.net/qq_32378713/article/details/131570304