open_o_tmpfile.c 1016 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#c */
  2. #define _GNU_SOURCE
  3. #include <assert.h>
  4. #include <fcntl.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <unistd.h>
  10. int main(void) {
  11. char buf[] = { 'a', 'b', 'c', 'd' };
  12. char buf2[] = { 'e', 'f', 'g', 'h' };
  13. int f, ret;
  14. size_t off;
  15. /* Create the temporary file and write to it. */
  16. f = open(".", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
  17. ret = write(f, buf, sizeof(buf));
  18. /* Interactivelly check if anything changed on directory. It hasn't. */
  19. /*puts("hit enter to continue");*/
  20. /*getchar();*/
  21. /* Read from the temporary file, and assert that
  22. * we read the same as we wrote. */
  23. lseek(f, 0, SEEK_SET);
  24. off = 0;
  25. while ((ret = read(f, buf2 + off, sizeof(buf) - off))) {
  26. off += ret;
  27. }
  28. close(f);
  29. assert(!memcmp(buf, buf2, sizeof(buf)));
  30. /* Assert that the file is gone now that we removed it. */
  31. return EXIT_SUCCESS;
  32. }