1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/mount.h>
4 #include <sys/stat.h>
5 #include <unistd.h>
6 #include <fcntl.h>
7 #include <string.h>
8 #include <errno.h>
9
10 // #define LOWERDIR "/tmp/overlayfs/lower"
11 // #define UPPERDIR "/tmp/overlayfs/upper"
12 // #define WORKDIR "/tmp/overlayfs/work"
13 // #define MERGEDDIR "/tmp/overlayfs/merged"
14
15 // void create_directories()
16 // {
17 // mkdir(LOWERDIR, 0755);
18 // mkdir(UPPERDIR, 0755);
19 // mkdir(WORKDIR, 0755);
20 // mkdir(MERGEDDIR, 0755);
21 // }
22 #define TMPDIR "/tmp"
23 #define OVERLAYFSDIR "/tmp/overlayfs"
24 #define LOWERDIR "/tmp/overlayfs/lower"
25 #define UPPERDIR "/tmp/overlayfs/upper"
26 #define WORKDIR "/tmp/overlayfs/work"
27 #define MERGEDDIR "/tmp/overlayfs/merged"
28
create_directories()29 void create_directories()
30 {
31 mkdir(TMPDIR, 0755);
32 mkdir(OVERLAYFSDIR, 0755);
33 mkdir(LOWERDIR, 0755);
34 mkdir(UPPERDIR, 0755);
35 mkdir(WORKDIR, 0755);
36 mkdir(MERGEDDIR, 0755);
37 printf("step1 : success\n");
38 }
39
create_lower_file()40 void create_lower_file()
41 {
42 char filepath[256];
43 snprintf(filepath, sizeof(filepath), "%s/lowerfile.txt", LOWERDIR);
44
45 int fd = open(filepath, O_CREAT | O_WRONLY, 0644);
46 if (fd < 0)
47 {
48 perror("Failed to create file in lowerdir");
49 exit(EXIT_FAILURE);
50 }
51 write(fd, "This is a lower layer file.\n", 28);
52 close(fd);
53 printf("step2 : success\n");
54 }
55
mount_overlayfs()56 void mount_overlayfs()
57 {
58 char options[1024];
59 snprintf(options, sizeof(options),
60 "lowerdir=%s,upperdir=%s,workdir=%s",
61 LOWERDIR, UPPERDIR, WORKDIR);
62
63 if (mount("overlay", MERGEDDIR, "overlay", 0, options) != 0)
64 {
65 perror("Mount failed");
66 exit(EXIT_FAILURE);
67 }
68 printf("OverlayFS mounted successfully.\n");
69 printf("step3 : success\n");
70 }
71
create_directory_in_merged()72 void create_directory_in_merged()
73 {
74 char dirpath[256];
75 snprintf(dirpath, sizeof(dirpath), "%s/newdir", UPPERDIR);
76
77 if (mkdir(dirpath, 0755) != 0)
78 {
79 perror("Failed to create directory in merged dir");
80 exit(EXIT_FAILURE);
81 }
82 printf("Directory created in merged: %s\n", dirpath);
83 printf("step4 : success\n");
84 }
85
main()86 int main()
87 {
88 create_directories();
89 mount_overlayfs();
90 create_directory_in_merged();
91 return 0;
92 }