You need to enable JavaScript to run this app. 如何根据进程PID获取Linux内核task_struct中comm字段对应的可执行文件名
优惠活动
大模型
产品
解决方案
定价
更多

如何根据进程PID获取Linux内核task_struct中comm字段对应的可执行文件名

通过PID获取进程对应可执行名(comm字段)的实现方案

用户态快速实现方案

不需要编写内核代码,利用Linux原生proc文件系统即可完成获取,内核本身已经会把每个进程task_struct的comm字段映射为可读取的虚拟文件:

  • 命令行直接获取:执行cat /proc/目标PID/comm,输出内容就是对应进程的可执行短名
  • 程序内自定义获取:按照固定路径拼接规则定位目标文件,读取内容即可,核心逻辑和直接cat完全一致,示例C代码如下:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

int get_comm_by_pid(pid_t pid, char *out_comm, size_t out_len) {
    char proc_path[64];
    FILE *comm_fp;
    // 拼接/proc下的comm文件路径
    snprintf(proc_path, sizeof(proc_path), "/proc/%d/comm", pid);
    comm_fp = fopen(proc_path, "r");
    if (!comm_fp) return -1;
    // 读取内容并移除末尾换行符
    if (fgets(out_comm, out_len, comm_fp)) {
        out_comm[strcspn(out_comm, "\n")] = '\0';
        fclose(comm_fp);
        return 0;
    }
    fclose(comm_fp);
    return -1;
}

注意:comm字段存储的可执行名有长度限制,最长为15个可打印字符(搭配1字节字符串结束符对应内核TASK_COMM_LEN的16字节数组定义),不是可执行文件的完整绝对路径,和ps命令输出中CMD列的短名内容完全一致。如果需要获取可执行文件的绝对路径,需要读取/proc/目标PID/exe符号链接的指向内容,不能通过comm字段得到。

内核态模块开发的实现方案

如果是在内核模块环境下开发,不需要依赖proc文件系统,可以直接操作进程的task_struct结构体获取comm内容:

  • 第一步:通过目标PID找到对应的task_struct指针,需要使用内核提供的RCU锁保护查找过程,避免访问到已经退出的进程悬空指针
  • 第二步:拿到合法的task_struct指针后,直接访问其comm成员,拷贝字符串到目标缓冲区即可
    核心实现示例:
#include <linux/sched.h>
#include <linux/rcupdate.h>
#include <linux/pid.h>
#include <linux/errno.h>

int get_kernel_comm_by_pid(pid_t pid, char *out_buf, size_t buf_len) {
    struct task_struct *target_task;
    // 开启RCU读锁,保护task查找过程
    rcu_read_lock();
    // 按虚拟PID查找对应进程的描述符
    target_task = pid_task(find_vpid(pid), PIDTYPE_PID);
    if (!target_task) {
        rcu_read_unlock();
        return -ESRCH;
    }
    // 拷贝comm字段到输出缓冲区,保证字符串终止
    strncpy(out_buf, target_task->comm, buf_len - 1);
    out_buf[buf_len - 1] = '\0';
    rcu_read_unlock();
    return 0;
}

注意:持RCU读锁的过程中不能执行任何可能导致阻塞的操作,否则会触发内核崩溃;拷贝comm内容时不要超过TASK_COMM_LEN定义的长度,避免越界破坏相邻内存。


内容的提问来源于stack exchange,提问作者Moises Rodan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.24 03:24:01