samples/vfs/mountinfo.c

Source file repositories/reference/linux-study-clean/samples/vfs/mountinfo.c

File Facts

System
Linux kernel
Corpus path
samples/vfs/mountinfo.c
Extension
.c
Size
6334 bytes
Lines
275
Domain
Support Tooling And Documentation
Bucket
samples
Inferred role
Support Tooling And Documentation: implementation source
Status
source implementation candidate

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

if (count < 0 || count > MAXMOUNTS) {
			errno = count < 0 ? errno : count;
			perror("listmount");
			return 1;
		}

		/* Walk the returned mntids and print info about each */
		for (i = 0; i < count; ++i) {
			int ret = dump_mountinfo(mntid[i], mnt_ns_id);

			if (ret != 0)
				return ret;
		}
		/* Set up last_mnt_id to pick up where we left off */
		last_mnt_id = mntid[count - 1];
	} while (count == MAXMOUNTS);
	return 0;
}

static void usage(const char * const prog)
{
	printf("Usage:\n");
	printf("%s [-e] [-p pid] [-r] [-h]\n", prog);
	printf("    -e: extended format\n");
	printf("    -h: print usage message\n");
	printf("    -p: get mount namespace from given pid\n");
	printf("    -r: recursively print all mounts in all child namespaces\n");
}

int main(int argc, char * const *argv)
{
	struct mnt_ns_info mni = { .size = MNT_NS_INFO_SIZE_VER0 };
	int pidfd, mntns, ret, opt;
	pid_t pid = getpid();
	bool recursive = false;

	while ((opt = getopt(argc, argv, "ehp:r")) != -1) {
		switch (opt) {
		case 'e':
			ext_format = true;
			break;
		case 'h':
			usage(argv[0]);
			return 0;
		case 'p':
			pid = atoi(optarg);
			break;
		case 'r':
			recursive = true;
			break;
		}
	}

	/* Get a pidfd for pid */
	pidfd = syscall(__NR_pidfd_open, pid, 0);
	if (pidfd < 0) {
		perror("pidfd_open");
		return 1;
	}

	/* Get the mnt namespace for pidfd */
	mntns = ioctl(pidfd, PIDFD_GET_MNT_NAMESPACE, NULL);
	if (mntns < 0) {
		perror("PIDFD_GET_MNT_NAMESPACE");
		return 1;
	}
	close(pidfd);

	/* get info about mntns. In particular, the mnt_ns_id */
	ret = ioctl(mntns, NS_MNT_GET_INFO, &mni);
	if (ret < 0) {
		perror("NS_MNT_GET_INFO");
		return 1;
	}

	do {
		int ret;

		ret = dump_mounts(mni.mnt_ns_id);
		if (ret)
			return ret;

		if (!recursive)
			break;

		/* get the next mntns (and overwrite the old mount ns info) */
		ret = ioctl(mntns, NS_MNT_GET_NEXT, &mni);
		close(mntns);
		mntns = ret;
	} while (mntns >= 0);

Annotation

Implementation Notes