ins_rm_mod.c 962 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /*
  2. http://stackoverflow.com/questions/5947286/how-can-linux-kernel-modules-be-loaded-from-c-code/38606527#38606527
  3. */
  4. #define _GNU_SOURCE
  5. #include <assert.h>
  6. #include <fcntl.h>
  7. #include <stdio.h>
  8. #include <sys/stat.h>
  9. #include <sys/syscall.h>
  10. #include <sys/types.h>
  11. #include <unistd.h>
  12. #include <stdlib.h>
  13. #define init_module(mod, len, opts) syscall(__NR_init_module, mod, len, opts)
  14. #define delete_module(name, flags) syscall(__NR_delete_module, name, flags)
  15. int main(void) {
  16. int fd = open("hello.ko", O_RDONLY);
  17. struct stat st;
  18. fstat(fd, &st);
  19. size_t image_size = st.st_size;
  20. void *image = malloc(image_size);
  21. read(fd, image, image_size);
  22. close(fd);
  23. if (init_module(image, image_size, "") != 0) {
  24. perror("init_module");
  25. return EXIT_FAILURE;
  26. }
  27. free(image);
  28. if (delete_module("hello", O_NONBLOCK) != 0) {
  29. perror("delete_modul");
  30. return EXIT_FAILURE;
  31. }
  32. return EXIT_SUCCESS;
  33. }