test_overlayfs.c 2.0 KB

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