内核获取进程的绝对路径

获取进程的绝对路径,记录供参考。

static int get_absolute_path_by_pid(int pid, char *buf, int len)
{
    int ret = 0;
    char link[100];
    char *p;
    struct path path;

    memset(buf, 0, len);
    sprintf(link, "/proc/%d/exe", pid);
    ret = kern_path( link, LOOKUP_FOLLOW, &path );
    p = httcsec_version_dpath3(&path, buf, len);
    if(IS_ERR(p))
        ret = PTR_ERR(p);
    else{
        len = strlen(p);
        memmove(buf, p, len);
    }

    return ret;
}

static int get_absolute_path_by_task(struct task_struct *task, char *buf, int len)
{
    int ret = 0;
    char *p;
    struct vm_area_struct * vma = NULL;
    struct path path;

    task_lock(task);
    if (task->mm && task->mm->mmap)
        vma = task->mm->mmap;
    else{
        ret = -1;
        goto out;
    }

    while (vma){
        if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file){
            path = vma->vm_file->f_path;
            break;
        }
        vma = vma->vm_next;
    }

out:
    task_unlock(task);

    if(!ret){
        memset(buf, 0, len);
        p = httcsec_version_dpath3(&path, buf, len);
        if(IS_ERR(p))
            ret = PTR_ERR(p);
        else{
            len = strlen(p);
            memmove(buf, p, len);
        }
    }

    return ret;
}

猜你喜欢

转载自blog.csdn.net/yh2869/article/details/84375889