温馨提示×

linux getppid能否获取指定进程id

小樊
83
2024-12-29 13:59:26
栏目: 智能运维
Linux服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

getppid() 是一个 Linux 系统中的系统调用,用于获取当前进程的父进程 ID

#include <stdio.h>
#include <unistd.h>

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

    pid_t target_pid = atoi(argv[1]);
    pid_t parent_pid = getppid(target_pid);

    if (parent_pid == -1) {
        perror("getppid");
        return 1;
    }

    printf("Parent process ID of PID %d is %d\n", target_pid, parent_pid);
    return 0;
}

将上述代码保存为 getppid_parent.c,然后使用以下命令编译:

gcc getppid_parent.c -o getppid_parent

运行编译后的程序,并传递一个进程 ID 作为参数:

./getppid_parent <pid>

其中 <pid> 是你想要查询的进程 ID。程序将输出该进程的父进程 ID。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:linux getppid有哪些限制条件

0