Skip to content

Instantly share code, notes, and snippets.

@mrunalp
Created August 25, 2015 23:16
Show Gist options
  • Save mrunalp/3d0e7d8e2b63658c47c0 to your computer and use it in GitHub Desktop.
Save mrunalp/3d0e7d8e2b63658c47c0 to your computer and use it in GitHub Desktop.
Mount tmpfs at /run in a process's mount namespace
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sched.h>
#include <unistd.h>
#include <errno.h>
#define pr_perror(fmt, ...) fprintf(stderr, "mountrun: " fmt ": %m\n", ##__VA_ARGS__)
#define BUFLEN 1024
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "Usage mountrun <pid>");
return EXIT_FAILURE;
}
int target_pid = atoi(argv[1]);
printf("Mounting run in mountnamespace of process: %d\n", target_pid);
char process_mnt_ns_fd[BUFLEN];
snprintf(process_mnt_ns_fd, BUFLEN - 1, "/proc/%d/ns/mnt", target_pid);
int fd = open(process_mnt_ns_fd, O_RDONLY);
if (-1 == fd) {
pr_perror("Failed to open mnt namespace fd %s", process_mnt_ns_fd);
exit(1);
}
// Join the mount namespace of the target process
if (setns(fd, 0) == -1) {
pr_perror("Failed to setns to %s", process_mnt_ns_fd);
exit(1);
}
// Switch to the root directory
if (chdir("/") == -1) {
pr_perror("Failed to chdir");
exit(1);
}
// Create the /run directory
if (mkdir("/run", 0755) == -1) {
if (errno != EEXIST) {
pr_perror("Failed to mkdir");
exit(1);
}
}
// Mount tmpfs at /run for systemd
if (mount("tmpfs", "/run", "tmpfs", MS_NODEV|MS_NOSUID|MS_NOEXEC, "mode=755,size=65536k") == -1) {
pr_perror("Failed to mount tmpfs at /run");
exit(1);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment