#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <dirent.h>

#define MAX_PATH_LENGTH 1024

char* get_process_path_by_name(const char* process_name) { DIR* dir; struct dirent* ent; char path[MAX_PATH_LENGTH]; char* result = NULL; pid_t pid; char* endptr;

dir = opendir("/proc");
if (dir == NULL) {
    perror("Failed to open /proc");
    return NULL;
}

while ((ent = readdir(dir)) != NULL) {
    pid = strtol(ent->d_name, &endptr, 10);
    if (*endptr != '\0') {
        continue;
    }

    snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
    FILE* fp = fopen(path, "r");
    if (fp) {
        char cmdline[MAX_PATH_LENGTH];
        fgets(cmdline, sizeof(cmdline), fp);
        fclose(fp);

        if (strstr(cmdline, process_name) != NULL) {
            snprintf(path, sizeof(path), "/proc/%d/exe", pid);
            result = realpath(path, NULL);
            break;
        }
    }
}

closedir(dir);
return result;

}

int main(int argc, char* argv[]) { if (argc != 2) { printf("Usage: %s <process_name> ", argv[0]); return 1; }

char* process_path = get_process_path_by_name(argv[1]);
if (process_path != NULL) {
    printf("%s\n", process_path);
    free(process_path);
} else {
    printf("Process not found\n");
}

return 0;

}

该代码首先打开/proc目录,读取其中的进程信息。对于每个进程,它打开其cmdline文件,读取其中的命令行信息,并检查其是否包含指定的进程名称。如果找到了匹配的进程,则使用realpath()函数获取其可执行文件的绝对路径,并返回该路径字符串。

使用该代码时,可以通过命令行参数指定要查找的进程名称,例如:

./get_process_path_by_name firefox

该命令会查找名为firefox的进程,并输出其可执行文件的绝对路径。如果找不到指定的进程,则输出'Process not found'。

C API 获取进程路径:根据进程名称查找可执行文件

原文地址: http://www.cveoy.top/t/topic/nnI3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录