Linux获取指定进程ID的秘诀

泥小猴系统教程网 2025-03-15 11:11:51 119阅读

Linux获取指定进程ID的秘诀

getppid() 系统调用在 Linux 系统中用于获取当前进程的父进程 ID。 然而,标准的 getppid() 函数并不能直接获取指定进程的父进程 ID。 上面的代码示例中,getppid(target_pid) 的用法是错误的。 getppid() 函数没有参数。

为了获取指定进程的父进程 ID,需要使用 /proc 文件系统。 以下是一个更正后的代码示例,它能够获取指定进程的父进程 ID:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

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

    pid_t target_pid = atoi(argv[1]);
    char path[256];
    snprintf(path, sizeof(path), "/proc/%d/stat", target_pid);

    FILE *fp = fopen(path, "r");
    if (fp == NULL) {
        perror("fopen");
        return 1;
    }

    char buffer[1024];
    fgets(buffer, sizeof(buffer), fp);
    fclose(fp);

    char *token = strtok(buffer, " ");
    for (int i = 0; i < 3; ++i) {
        token = strtok(NULL, " ");
    }

    pid_t parent_pid = atoi(token);

    printf("Parent process ID of PID %d is %d
", target_pid, parent_pid);
    return 0;
}
登录后复制

这个程序通过读取 /proc//stat 文件来获取进程信息。 该文件包含进程的各种信息,包括父进程 ID。 程序解析该文件,提取并打印父进程 ID。

编译和运行方法与之前相同:

gcc getppid_parent.c -o getppid_parent
./getppid_parent <pid>
登录后复制

请记住,只有具有足够权限的用户才能访问 /proc 文件系统中的信息。

文章版权声明:除非注明,否则均为泥小猴系统网网络收集而来,如有任何问题请联系站长。

相关阅读

目录[+]