ubase

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

mountpoint.c (1668B)


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