C - Lstat on/proc/pid/exe

Ami*_*ina 1 c symlink system-calls opensuse

我正在尝试使用lstat获取/ proc/pid/exe文件的大小(以字节为单位).这是我的代码:

int     main(int argc, char *argv[]) 
{   
 struct stat    sb;
 char       *linkname;
 ssize_t    r;

  if (argc != 2) 
  {
    fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  if (lstat(argv[1], &sb) == -1) 
  {
    perror("lstat");
    exit(EXIT_FAILURE);
  }

  printf("sb.st_size %d\n", sb.st_size);   

  exit(EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)

似乎sb.st_size总是等于0,我不明白为什么.另外,此示例是从readlink(2)手册页中提取的.

编辑:我正在努力让它在openSUSE上工作.

在此先感谢您的帮助.

Nom*_*mal 6

在该文件中的/ proc不是普通的文件.对于大多数人来说,stat()等等.回来.st_size == 0.

特别是,/proc/PID/exe它不是一个符号链接或硬链接,而是一个特殊的伪文件,其行为大多类似于符号链接.

(如果需要,可以检测procfs文件检查.st_dev字段.比较.st_devlstat("/proc/self/exe",..)例如获得的.)

要根据其PID获取特定execubtable的路径,我建议使用依赖于返回值的方法readlink():

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

/* Creative Commons CC0: Public Domain dedication
 * (In jurisdictions without public domain, this example program
 *  is licensed under the Creative Commons CC0 license.)
 *
 * To the extent possible under law, Nominal Animal has waived all
 * copyright and related or neighboring rights to this example program.
 *
 * In other words, you are free to use it in any way you wish,
 * but if it breaks something, you get to keep all the pieces.
*/

/** exe_of() - Obtain the executable path a process is running
 * @pid: Process ID
 * @sizeptr: If specified, the allocated size is saved here
 * @lenptr: If specified, the path length is saved here
 * Returns the dynamically allocated pointer to the path,
 * or NULL with errno set if an error occurs.
*/
char *exe_of(const pid_t pid, size_t *const sizeptr, size_t *const lenptr)
{
    char   *exe_path = NULL;
    size_t  exe_size = 1024;
    ssize_t exe_used;
    char    path_buf[64];
    int     path_len;

    path_len = snprintf(path_buf, sizeof path_buf, "/proc/%ld/exe", (long)pid);
    if (path_len < 1 || path_len >= sizeof path_buf) {
        errno = ENOMEM;
        return NULL;
    }

    while (1) {

        exe_path = malloc(exe_size);
        if (!exe_path) {
            errno = ENOMEM;
            return NULL;
        }

        exe_used = readlink(path_buf, exe_path, exe_size - 1);
        if (exe_used == (ssize_t)-1)
            return NULL;

        if (exe_used < (ssize_t)1) {
            /* Race condition? */
            errno = ENOENT;
            return NULL;
        }

        if (exe_used < (ssize_t)(exe_size - 1))
            break;

        free(exe_path);
        exe_size += 1024;
    }

    /* Try reallocating the exe_path to minimum size.
     * This is optional, and can even fail without
     * any bad effects. */
    {
        char *temp;

        temp = realloc(exe_path, exe_used + 1);
        if (temp) {
            exe_path = temp;
            exe_size = exe_used + 1;
        }
    }

    if (sizeptr)
        *sizeptr = exe_size;

    if (lenptr)
        *lenptr = exe_used;

    exe_path[exe_used] = '\0';
    return exe_path;
}

int main(int argc, char *argv[])
{
    int   arg;
    char *exe;
    long  pid;
    char  dummy;

    if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
        printf("\n");
        printf("Usage: %s [ -h | --help ]\n", argv[0]);
        printf("       %s PID [ PID ... ]\n", argv[0]);
        printf("\n");
        return 0;
    }

    for (arg = 1; arg < argc; arg++)
        if (sscanf(argv[arg], " %ld %c", &pid, &dummy) == 1 && pid > 0L) {
            exe = exe_of((pid_t)pid, NULL, NULL);
            if (exe) {
                printf("Process %ld runs '%s'.\n", pid, exe);
                free(exe);
            } else
                printf("Process %ld: %s.\n", pid, strerror(errno));
        } else {
            printf("%s: Invalid PID.\n", argv[arg]);
            return 1;
        }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面,该exe_of()函数返回伪符号链接/proc/PID/exe指向的动态分配副本,也可选择存储分配的大小和/或路径长度.(上面的示例程序不需要它们,因此它们是NULL.)

这个想法非常简单:为大多数情况分配一个足够大的初始动态指针,但不是非常大.保留字符串结尾NUL字节的最后一个字节.如果返回的大小readlink()与给定的缓冲区长度相同 - 它不会添加终止字符串结尾的NUL字节 - 那么缓冲区可能太短; 丢弃它,分配更大的缓冲区,然后重试.

同样,如果您希望读取伪文件的全部内容/proc/,则不能使用lstat()/ stat()first来查找可能需要的缓冲区大小; 你需要分配一个缓冲区,尽可能多地读取,并在必要时重新分配一个更大的缓冲区.(我也可以显示示例代码.)

有问题吗?