LinuxのCアプリケーションは、USBディスクがマウントされているかどうかを検出します。

LinuxのCアプリケーションは、USBディスクがマウントされているかどうかを検出します。

CアプリケーションにUSBディスクがマウントされていることを確認したいと思います。スクリプトでは、mount | grep /mnt(udevがUSBドライブのマウントポイントをマウントする)を介してこれを行うことができることを知っていますが、Cアプリケーションでこれを行う必要があります。以前は system("sh script.sh") を使用してこれを行いましたが、このコードが非常に重要なスレッドで実行されていたため、深刻な問題が発生しました。

ベストアンサー1

マウントポイントの完全なリストを確認する必要がある場合は、スレッドセーフなgetmntent(3)GNU拡張を使用してくださいgetmntent_r(3)

特定のディレクトリにマウントされたファイルシステムがあるかどうかをすばやく確認するには、stat(2)このシリーズの機能の1つを使用してください。たとえば、/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");
}

おすすめ記事