how can i show the size of files in /proc? it should not be size zero

≯℡__Kan透↙ 提交于 2019-11-26 10:57:05

Those are not really files on disk (as you mention) but they are also not files in memory - the names in /proc correspond to calls into the running kernel in the operating system, and the contents are generated on the fly.

The system doesn't know how large the files would be without generating them, but if you read the "file" twice there's no guarantee you get the same data because the system may have changed.

You might be looking for the program sysctl -a instead.

Things in /proc are not really files. In most cases, they're not even files in memory. When you access these files, the proc filesystem driver performs a system call that gets data appropriate for the file, and then formats it for output. This is usually dynamic data that's constructed on the fly. An example of this is /proc/net/arp, which contains the current ARP cache.

Getting the size of these things can only be done by formatting the entire output, so it's not done just when listing the file. If you want the sizes, use wc -c as you did.

The /proc/ filesystem is an "illusion" maintained by the kernel, which does not bother giving the size of (most of) its pseudo-files (since computing that "real" size would usually involve having built the entire textual pseudo-file's content), and expects most [pseudo-] textual files from /proc/ to be read in sequence from first to last byte (i.e. till EOF), in reasonably sized (e.g. 1K) blocks. See proc(5) man page for details.

So there is no way to get the true size (of some file like /proc/self/maps or /proc/sys/net/ipv4/ip_forward) in a single syscall (like stat(2), because it would give a size of 0, as reported by stat(1) or ls(1) commands). A typical way of reading these textual files might be

FILE* f = fopen("/proc/self/maps", "r"); 
                // or some other textual /proc file, 
                // e.g. /proc/sys/net/ipv4/ip_forward
if (f) 
  {
      do {
        // you could use readline instead of fgets
        char line[256];
        memset (line, 0, sizeof(line));
        if (NULL == fgets(line, sizeof(line), f))
          break;
        // do something with line, for example:
        fputs(line, stdout);
      } while (!feof (f));
    fclose (f);
  }

Of course, some files (e.g. /proc/self/cmdline) are documented as possibly containing NUL bytes. You'll need some fread for them.

It's not really a file in the memory, it's an interface between the user and the kernel.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!