内核模块中task_cgroup_path函数在5.14-6.8版本编译失败问题
内核模块中task_cgroup_path函数在5.14+内核编译失败的解决办法
问题背景
我在内核模块中使用task_cgroup_path函数,该最小可复现示例在4.18版本内核可正常编译,但在5.14到6.8版本内核下编译失败。
原代码
#include <linux/module.h> //#include <linux/printk.h> //#include <linux/time.h> #include <linux/cgroup.h> struct timespec64 ts; int init_module(void) { char *cpath_buf; int cpath_ret; cpath_buf = kmalloc(PATH_MAX, GFP_KERNEL); ktime_get_real_ts64((struct timespec64 *)&ts); cpath_ret = task_cgroup_path(current, cpath_buf, PATH_MAX); // pr_info("Hello world (%lld/%ld).\n", ts.tv_sec, ts.tv_nsec); return 0; } void cleanup_module(void) { pr_info("Goodbye world 0.\n"); } MODULE_LICENSE("GPL");
编译错误信息
root@kerndev:~/tst_time# make make -C /lib/modules/6.8.0-55-generic/build M=/root/tst_time modules make[1]: Entering directory '/usr/src/linux-headers-6.8.0-55-generic' warning: the compiler differs from the one used to build the kernel The kernel was built by: x86_64-linux-gnu-gcc-13 (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 You are using: gcc-13 (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 CC [M] /root/tst_time/m_timespec.o /root/tst_time/m_timespec.c: In function ‘init_module’: /root/tst_time/m_timespec.c:15:21: error: implicit declaration of function ‘task_cgroup_path’; did you mean ‘sock_cgroup_ptr’? [-Werror=implicit-function-declaration] 15 | cpath_ret = task_cgroup_path(current, cpath_buf, PATH_MAX); | ^~~~~~~~~~~~~~~~ | sock_cgroup_ptr cc1: some warnings being treated as errors make[3]: *** [scripts/Makefile.build:243: /root/tst_time/m_timespec.o] Error 1 make[2]: *** [/usr/src/linux-headers-6.8.0-55-generic/Makefile:1925: /root/tst_time] Error 2 make[1]: *** [Makefile:240: __sub-make] Error 2 make[1]: Leaving directory '/usr/src/linux-headers-6.8.0-55-generic' make: *** [Makefile:6: all] Error 2 root@kerndev:~/tst_time# uname -a Linux kerndev 6.8.0-55-generic #57-Ubuntu SMP PREEMPT_DYNAMIC Wed Feb 12 23:42:21 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
解决方案
task_cgroup_path函数在5.14版本内核中被移除,官方替代接口为task_cgroup_path_from_root,以下是适配后的代码:
#include <linux/module.h> #include <linux/cgroup.h> #include <linux/sched.h> #include <linux/slab.h> struct timespec64 ts; int init_module(void) { char *cpath_buf; int cpath_ret; cpath_buf = kmalloc(PATH_MAX, GFP_KERNEL); if (!cpath_buf) { pr_err("kmalloc failed for cgroup path buffer\n"); return -ENOMEM; } // 使用task_cgroup_path_from_root替代原task_cgroup_path // 传入NULL表示使用默认根cgroup cpath_ret = task_cgroup_path_from_root(current, cpath_buf, PATH_MAX, NULL); if (cpath_ret > 0) { pr_info("Current task cgroup path: %.*s\n", cpath_ret, cpath_buf); } else if (cpath_ret < 0) { pr_err("Failed to get cgroup path, err: %d\n", cpath_ret); } kfree(cpath_buf); return 0; } void cleanup_module(void) { pr_info("Goodbye world 0.\n"); } MODULE_LICENSE("GPL");
关键说明
task_cgroup_path_from_root新增了根cgroup参数,传入NULL即可实现原task_cgroup_path的功能;- 新增了内存分配失败的错误检查,避免空指针访问;
- 函数返回值为正表示成功写入的字符数,负数表示错误码,需根据返回值做相应处理。
内容的提问来源于stack exchange,提问作者flav
相关产品推荐
相关产品推荐

