Rafael Baptista
Rafael Baptista

Reputation: 11499

Detect when a file descriptor is from /proc

Files from the /proc directory cannot be read in the normal way. In particular, fstat will tell you that the file is zero size even when there is content.

This plays havoc with some of my file reading code that first asks for the file size before reading. Essentially you have to read files from /proc more like you would read a pipe or stdin - read until you get the EOF.

But, how can I detect if a file descriptor, or FILE* is from /proc?

Looking at the content of stat after doing an fstat I don't see any clear way of detecting this. Nothing in st_mode, or ownership or permissions can definitively tell me its from /proc.

The device id looks promising - on the systems I've tried it comes back as 3, where regular disks have a higher number ( like 801). But is it always guaranteed to be 3? I can't find an official supported way.

Looking for an answer in c/c++

Upvotes: 0

Views: 443

Answers (1)

Rafael Baptista
Rafael Baptista

Reputation: 11499

Ok answer found.

#include <sys/statfs.h>
#include <linux/magic.h>

struct statfs fs;
fstatfs( fileno( file ), &fs );
bool isProc = ( fs.f_type == PROC_SUPER_MAGIC ) ? true : false;

Upvotes: 1

Related Questions