main.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. // #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. {
  28. mkdir(TMPDIR, 0755);
  29. mkdir(OVERLAYFSDIR, 0755);
  30. mkdir(LOWERDIR, 0755);
  31. mkdir(UPPERDIR, 0755);
  32. mkdir(WORKDIR, 0755);
  33. mkdir(MERGEDDIR, 0755);
  34. printf("step1 : success\n");
  35. }
  36. void create_lower_file()
  37. {
  38. char filepath[256];
  39. snprintf(filepath, sizeof(filepath), "%s/lowerfile.txt", LOWERDIR);
  40. int fd = open(filepath, O_CREAT | O_WRONLY, 0644);
  41. if (fd < 0)
  42. {
  43. perror("Failed to create file in lowerdir");
  44. exit(EXIT_FAILURE);
  45. }
  46. write(fd, "This is a lower layer file.\n", 28);
  47. close(fd);
  48. printf("step2 : success\n");
  49. }
  50. void mount_overlayfs()
  51. {
  52. char options[1024];
  53. snprintf(options, sizeof(options),
  54. "lowerdir=%s,upperdir=%s,workdir=%s",
  55. LOWERDIR, UPPERDIR, WORKDIR);
  56. if (mount("overlay", MERGEDDIR, "overlay", 0, options) != 0)
  57. {
  58. perror("Mount failed");
  59. exit(EXIT_FAILURE);
  60. }
  61. printf("OverlayFS mounted successfully.\n");
  62. printf("step3 : success\n");
  63. }
  64. void create_directory_in_merged()
  65. {
  66. char dirpath[256];
  67. snprintf(dirpath, sizeof(dirpath), "%s/newdir", UPPERDIR);
  68. if (mkdir(dirpath, 0755) != 0)
  69. {
  70. perror("Failed to create directory in merged dir");
  71. exit(EXIT_FAILURE);
  72. }
  73. printf("Directory created in merged: %s\n", dirpath);
  74. printf("step4 : success\n");
  75. }
  76. int main()
  77. {
  78. create_directories();
  79. mount_overlayfs();
  80. create_directory_in_merged();
  81. return 0;
  82. }