在 solaris 上如何以编程方式获取 运行 进程的可执行文件的完整路径?

On solaris how to get the full path of executable of running process programatically?

在Ubuntu上,我们可以通过读取/proc/'pid'/exe.

提取运行进程的exe的完整路径

在 solaris 上,/proc/'pid' 中没有 'exe' 文件。 我读了psinfo。但它只给出了过程和参数的名称。它没有 exe 的完整路径。 在 solaris 上我们如何做到这一点? 我的solaris版本是11.3.

通过命令,你可以得到exe的完整路径运行,像这样:

# ls -l /proc/<pid>/path/a.out

例如

# ls -l /proc/$$/path/a.out
lrwxrwxrwx   1 root     root           0 Nov 24 17:19 /proc/14921/path/a.out -> /usr/bin/bash

这样就可以得到可执行路径

更方便的方法是:

# readlink -f /proc/<pid>/path/a.out

例如:

# readlink -f /proc/$$/path/a.out
/usr/bin/bash

您可以通过编程方式执行此操作:

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

#define BUF_SIZE 1024

int main(int argc, char *argv[]) {
    char outbuf[BUF_SIZE] = {'[=14=]'};
    char inbuf[BUF_SIZE] = {'[=14=]'};
    ssize_t len;

    if (argc != 2) {
            printf ("Invalid argument\n");
            return -1;
    }

    snprintf (inbuf, BUF_SIZE, "/proc/%s/path/a.out", argv[1]);

    if ((len = readlink(inbuf, outbuf, BUF_SIZE-1)) != -1) {
            outbuf[len] = '[=14=]';
    } else {
            perror ("readlink failed: ");
            return -1;
    }

    printf ("%s\n", outbuf);
    return 0;
}

它的用法:

# ./a.out <pid>  

对于 Solaris 不确定,但对于一些旧的 unix,唯一可以检索的是 argv[0] 中的命令名称。然后我们必须在 PATH 环境变量 中以正确的顺序 搜索该命令以找到该命令的完整路径。

有点手册但防弹。