Get device filesystem path from dev_t on macOS - c

If I have a 32-bit integer BSD device number dev_t (e.g. 0x1000004) on macOS (Darwin), how can I get the corresponding filesystem path for this device (e.g. "/dev/disk1s4")?

You have to enumerate the mounted file systems and look for one who's device ID matches. You can use getfsstat() for the enumeration. That fills in struct statfs structures. Compare the field f_fsid.val[0] of each structure to the dev_t you're looking for. If they match, then that struct statfs is the one for the device you're looking for and you can examine its other fields for the info you're looking for. In particular, the f_mntfromname is the device path.

find /dev -type b -ls
, And check the output for major/minor == {0x1000,4}
Or: find / -type b -ls if need to search the entire file system.
BTW: there could be more entries, referring to the same {major,minor} combination.

Related

readdir is returning lots of all-0xFF 8.3 names from fat32 filesystem

I'm working on an ESP32 platform with IDF 4.1, using code like this:
struct dirent * dirent;
while((dirent = readdir(dir)) != nullptr) {
ESP_LOGI("ConfigServer", "Found %s, id %d, type %d", dirent->d_name, dirent->d_ino, dirent->d_type);
if(dirent->d_name[0] == '\377') {
++invalid_ctr;
} else {
// do something with the file info
}
}
closedir(dir);
I had to add the bit where invalid_ctr is incremented, because I started getting loads of iterations where dirent->d_name was "\377\377\377\377\377\377\377\377.\377\377\377" (rendered as inverse-video "?" characters in my terminal). The code not shown involves feeding that name to stat(), which would return the same values as the last valid file encountered. The log entry would look like this:
I (608261) ConfigServer: Found ��������.���, id 0, type 2
Type 2 represents a directory. This is happening on a partition on the onboard flash, formatted by the IDF library's "format if mount failed" option at mount. So perhaps my assumption of FAT32 is invalid. I do know that IDF uses FatFs internally.
Is this indicative of an error on the filesystem? Is it expected to need to filter out such trash on a typical iteration with readdir()?
The FAT component in ESP IDF has support for long file names disabled by default. Run idf.py menuconfig, then "Component config → FAT Filesystem support → Long filename support" to enable it.

Linux programming: which device a file is in

I would like to know which entry under /dev a file is in. For example, if /dev/sdc1 is mounted under /media/disk, and I ask for /media/disk/foo.txt, I would like to get /dev/sdc as response.
Using stat system call on that file I will get its partition major and minor numbers (8 and 33, for sdc1). Now I need to get the "root" device (sdc) or its major/minor from that. Is there any syscall or library function I could use to link a partition to its main device? Or even better, to get that device directly from the file?
brw-rw---- 1 root floppy 8, 32 2011-04-01 20:00 /dev/sdc
brw-rw---- 1 root floppy 8, 33 2011-04-01 20:00 /dev/sdc1
Thanks in advance!
The quick and dirty version: df $file | awk 'NR == 2 {print $1}'.
Programmatically... well, there's a reason I started with the quick and dirty version. There's no portable way to programmatically get the list of mounted filesystems. (getmntent() gets fstab entries, which is not the same thing.) Moreover, you can't even parse the output of mount(8) reliably; on different Unixes, the mountpoint may be the first or the last item. The most portable way to do this ends up being... parsing df output (And even that is iffy, as you noticed with the partition number.). So you're right back to the quick and dirty shell solution anyway, unless you want to traverse /dev and look for block devices with matching major(st_rdev) (major() being from sys/types.h).
If you restrict this to Linux, you can use /proc/mounts to get the list of mounted filesystems. Other specific Unixes can similarly be optimized: for example, on OS X and I think FreeBSD, you can use sysctl() on the vfs tree to get mountpoints. At worst you can find and use the appropriate header file to decipher whatever the mount table file is (and yes, even that varies: on Solaris it's /etc/mnttab, on many other systems it's /etc/mtab, some systems put it in /var/run instead of /etc, and on many Linuxes it's either nonexistent or a symlink to /proc/mounts). And its format is different on pretty much every Unix-like OS.
The information you want exists in sysfs which exposes the linux device tree. This models the relationships between the devices on the system and since you are trying to determine a parent disk device from a partition, this is the place to look. I don't know if there are any hard and fast rules you can rely on to stop your code breaking with future versions of the kernel, but the kernel developers do try to maintain sysfs as a stable interface.
If you look at /sys/dev/block/<major>:<minor>, you'll see it is a symlink with the tail components being block/<disk-device-name>/<partition-device-name>. If you were to perform a readlink(2) system call on that, you could parse the link destination to get the disk device name. In shell (since it's easier to express this way, but doing it in C will be pretty easy):
$ echo $(basename $(dirname $(readlink /sys/dev/block/8:33)))
sdc
Alternatively, you could take advantage of the nesting of partition directories in the disk directories (again in shell, but from C, its an open(2), read(2), and close(2)):
$ cat /sys/dev/block/8:33/../dev
8:32
That assumes your starting major:minor is actually for a partition, not some other sort of non-nested device.
What you looking for is impossible - there is no 1:1 connection between a block device file and the partition it is describing.
Consider:
You can create multiple block device files with different names (but the same major and minor numbers) and they are indistinguishable (N:1)
You can use a block device file as an argument to mount to mount a partition and then delete the block device file leaving the partition mounted. (0:1)
So there is no way to do what you want except in a few specific and narrow cases.
Major number will tell you which device it is: 3 - IDE on 1st controller, 22 - IDE on 2nd controller and 8 for SCSI.
Minor number will tell you partition number and - for IDE devices - if it's primary or secondary drive. This calculation is different for IDE and SCSI.
For IDE it is: x*64 + p, x is drive number on the controller (0 or 1) and p is partition
For SCSI it is: y*16 + p, where y is drive number and p is partition
Not a syscall, but:
df -h /path/to/my/file
From https://unix.stackexchange.com/questions/128471/determine-what-device-a-directory-is-located-on
So you could look at df's source code and see what it does.
I realize this post is old, but this question was the 2nd result in my search and no one has mentioned df -h

How to get inode count of a filesystem on Solaris/Unix?

I was invoking the following command and reading the outpup df -F ufs -o i. It worked fine initially but then started to fail for the reason reported and explained here http://wesunsolve.net/bugid/id/6795242.
Although the solution suggested on the above link might work but it is ugly and I want a permanent solution. So, really looking for c api on Solaris/Unix that would give me the total and available number of inodes given a filesystem.
Sample/Example is much appreciated.
The statvfs system call can be used to retrieve file system statistics including the number of total inodes and the number of free inodes. Use the system call to retrieve a statvfs structure and then inspect the f_files and f_ffree fields to determine the number of inodes and the number of free inodes, respectively.
Example:
#include <statvfs.h>
struct statvfs buffer;
int status;
fsfilcnt_t total_inodes;
fsfilcnt_t free_inodes;
...
status = statvfs("/home/betaylor/file_in_filesystem", &buffer);
total_inodes = buffer.f_files;
free_inodes = buffer.f_ffree;
...
What you want is statvfs -- see the man page on the Solaris web site.

How many files can i have opened at once?

On a typical OS how many files can i have opened at once using standard C disc IO?
I tried to read some constant that should tell it, but on Windows XP 32 bit that was a measly 20 or something. It seemed to work fine with over 30 though, but i haven't tested it extensively.
I need about 400 files opened at once at max, so if most modern OS's support that, it would be awesome. It doesn't need to support XP but should support Linux, Win7 and recent versions of Windows server.
The alternative is to write my own mini file system which i want to avoid if possible.
On Linux, this is dependent on the amount of available file descriptors.
You can use ulimit -n to set / show the number of available FD's per shell.
See these instructions to how to check (or change) the value of available total FD:s in Linux.
This IBM support article suggests that on Windows the number is 512, and you can change it in the registry (as instructed in the article)
As open() returns the fd as int - size of int limits also the upper limit.
(irrelevant as INT_MAX is a lot)
A process can query the limit using the getrlimit system-call.
#include<sys/resource.h>
struct rlimit rlim;
getrlimit(RLIMIT_NOFILE, &rlim);
printf("Max number of open files: %d\n", rlim.rlim_cur-1);
FYI, as root, you have first to modify the 'nofile' item in /etc/security/limits.conf . For example:
* hard nofile 10240
* soft nofile 10240
(changes in limits.conf typically take effect when the user logs in)
Then, users can use the ulimit -n bash command. I've tested this with up to 10,240 files on Fedora 11.
ulimit -n <max_number_of_files>
Lastly, all this is limited by the kernel limit, given by: (I guess you could echo a value into this to go even higher... at your own risk)
cat /proc/sys/fs/file-max
Also, see http://www.karakas-online.de/forum/viewtopic.php?t=9834

How do I find the size of mounted USB flash drive in C?

I have a flash drive device (/dev/sda1) mounted to /mnt on an embedded linux system (kernel 2.6.23). Using C how do I work out the size of the drive?
On Linux, if you're not worried about portability (C doesn't know about drives, so any such specific code will be unportable), use statfs():
struct statfs fsb;
if(statfs("/mnt", &fsb) == 0)
printf("device has %ld blocks, each %ld bytes\n", fsb.f_blocks, fsb.f_bsize);
Read and parse a number in device's sysfs entry. In your case,
Full device (all partitions and partition table): /sys/block/sda/size
Logical partition on this device: /sys/block/sda/sda1/size
The device does not have to be mounted yet.
If you have no problem using external tools, exec this :
df -h | grep -i /dev/sda1
using popen, and parse the resulting line with strtok.

Resources