xref: /linux-tools/ebpf/kernel-samples-bpf/syscall_tp_openat_user.c (revision 74ce4ce33d5b8318cee71b38976a25818e666ff3)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <errno.h>
5 #include <signal.h>
6 #include <string.h>
7 #include <linux/bpf.h>
8 #include <bpf/bpf.h>
9 #include <bpf/libbpf.h>
10 
11 #include "bpf_load.h"
12 #include "syscall_tp.h"
13 
14 struct bpf_object *obj = NULL;
15 struct ring_buffer *ring_buf = NULL;
16 static void int_exit(int sig) {
17     if (ring_buf) {
18         ring_buffer__free(ring_buf);
19         ring_buf= NULL;
20     }
21     if (obj){
22         bpf_object__close(obj);
23         obj = NULL;
24     }
25 }
26 
27 static int event_handler(void *_ctx, void *data, size_t size) {
28     if (size != sizeof(struct open_event)){
29         printf("receive unmatch size %d\n", (int)size);
30         return 0;
31     }
32     struct open_event* event = (struct open_event*)data;
33     printf("[%d] open %s\n", event->pid, event->fname);
34     return 0;
35 }
36 
37 int main(int argc, char *argv[]) {
38     int fd;
39     if (load_bpf_file("./syscall_tp_openat_kern.o")) {
40         perror("fail to load bpf file");
41         return 1;
42     }
43     fd = map_fd[0];
44     /*
45 	obj = bpf_object__open_file("./syscall_tp_openat_kern.o", NULL);
46 	if (libbpf_get_error(obj)) {
47         perror("Fail to open bpf file");
48         return 1;
49     }
50 	if (bpf_object__load(obj)) {
51         perror("Fail to load bpf prog");
52         return 1;
53     }
54 	fd = bpf_object__find_map_fd_by_name(obj, "opens");
55     if (fd<0) {
56         perror("Fail to locate map");
57         return 1;
58     }
59     */
60     ring_buf = ring_buffer__new(fd, event_handler, NULL, NULL);
61     if (!ring_buf) {
62         perror("Fail to alloc ring buf");
63         return 1;
64     }
65 	signal(SIGINT, int_exit);
66 	signal(SIGTERM, int_exit);
67     while (ring_buffer__poll(ring_buf, -1) >= 0) {}
68     int_exit(0);
69 
70     return 0;
71 }
72