ubase

suckless linux base utils
git clone git://git.2f30.org/ubase.git
Log | Files | Refs | README | LICENSE

mountpoint.c (1641B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <sys/stat.h>
      3 #include <sys/types.h>
      4 
      5 #include <mntent.h>
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 #include <string.h>
      9 #include <unistd.h>
     10 
     11 #include "util.h"
     12 
     13 static void
     14 usage(void)
     15 {
     16 	eprintf("usage: %s [-dqx] target\n", argv0);
     17 }
     18 
     19 int
     20 main(int argc, char *argv[])
     21 {
     22 	int dflag = 0, qflag = 0, xflag = 0;
     23 	int ret = 0;
     24 	struct mntent *me = NULL;
     25 	FILE *fp;
     26 	struct stat st1, st2;
     27 
     28 	ARGBEGIN {
     29 	case 'd':
     30 		dflag = 1;
     31 		break;
     32 	case 'q':
     33 		qflag = 1;
     34 		break;
     35 	case 'x':
     36 		xflag = 1;
     37 		break;
     38 	default:
     39 		usage();
     40 	} ARGEND;
     41 
     42 	if (argc < 1)
     43 		usage();
     44 
     45 	if (stat(argv[0], &st1) < 0) {
     46 		if (qflag)
     47 			return 1;
     48 		eprintf("stat %s:", argv[0]);
     49 	}
     50 
     51 	if (xflag) {
     52 		if (!S_ISBLK(st1.st_mode)) {
     53 			if (qflag)
     54 				return 1;
     55 			eprintf("stat: %s: not a block device\n",
     56 				argv[0]);
     57 		}
     58 		printf("%u:%u\n", major(st1.st_rdev),
     59 		       minor(st1.st_rdev));
     60 		return 0;
     61 	}
     62 
     63 	if (!S_ISDIR(st1.st_mode)) {
     64 		if (qflag)
     65 			return 1;
     66 		eprintf("stat %s: not a directory\n", argv[0]);
     67 	}
     68 
     69 	if (dflag) {
     70 		printf("%u:%u\n", major(st1.st_dev),
     71 		       minor(st1.st_dev));
     72 		return 0;
     73 	}
     74 
     75 	fp = setmntent("/proc/mounts", "r");
     76 	if (!fp) {
     77 		if (qflag)
     78 			return 1;
     79 		eprintf("setmntent %s:", "/proc/mounts");
     80 	}
     81 	while ((me = getmntent(fp)) != NULL) {
     82 		if (stat(me->mnt_dir, &st2) < 0) {
     83 			if (qflag)
     84 				return 1;
     85 			eprintf("stat %s:", me->mnt_dir);
     86 		}
     87 		if (st1.st_dev == st2.st_dev &&
     88 		    st1.st_ino == st2.st_ino)
     89 			break;
     90 	}
     91 	endmntent(fp);
     92 
     93 	if (me == NULL)
     94 		ret = 1;
     95 
     96 	if (!qflag)
     97 		printf("%s %s a mountpoint\n", argv[0],
     98 		       !ret ? "is" : "is not");
     99 
    100 	return ret;
    101 }