我想检查USB磁盘是否安装在C应用程序中。我知道在脚本中我可以通过mount | grep / mnt(udev挂载USB驱动器的挂载点),但是我需要在C应用程序中执行此操作。之前我曾经使用system(“ sh script.sh”)来完成此操作,但是这样做会导致一些严重的问题,因为此代码在时间紧迫的线程中运行。
如果需要检查安装点的完整列表,请使用getmntent(3)
或其线程安全的GNU扩展getmntent_r(3)
。
如果只想快速检查给定目录上是否装有文件系统,请使用该stat(2)
系列中的功能之一。例如,如果要检查是否/mnt
已安装文件系统,则可以执行以下操作:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
struct stat mountpoint;
struct stat parent;
/* Get the stat structure of the directory...*/
if stat("/mnt", &mountpoint) == -1) {
perror("failed to stat mountpoint:");
exit(EXIT_FAILURE);
}
/* ... and its parent. */
if stat("/mnt/..", &parent) == -1) {
perror("failed to stat parent:");
exit(EXIT_FAILURE);
}
/* Compare the st_dev fields in the results: if they are
equal, then both the directory and its parent belong
to the same filesystem, and so the directory is not
currently a mount point.
*/
if (mountpoint.st_dev == parent.st_dev) {
printf("No, there is nothing mounted in that directory.\n");
} else {
printf("Yes, there is currently a filesystem mounted.\n");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句