Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <stdlib.h>
  5. #include <limits.h>
  6. #include <errno.h>
  7.  
  8. #ifndef PATH_MAX
  9. #define PATH_MAX (4096)
  10. #endif
  11.  
  12. const char pref_string[] =  \
  13. "#!/usr/bin/env python3\n"  \
  14. "import os\n"               \
  15. "print(1";
  16.  
  17. int
  18. main(int argc, char **argv)
  19. {
  20.     if (argc < 2) {
  21.         return EXIT_SUCCESS;
  22.     }
  23.  
  24.     const char *dir = getenv("XDG_RUNTIME_DIR");
  25.     if (!dir) {
  26.         dir = getenv("TMPDIR");
  27.     }
  28.     if (!dir) {
  29.         dir = "/tmp/";
  30.     }
  31.  
  32.     char file_path[PATH_MAX];
  33.     int file_num = 0, fd = -1;
  34.     do {
  35.         unsigned expected = snprintf(file_path, sizeof(file_path), "%s/tmp_%d.py", dir, file_num++);
  36.         if (expected > sizeof(file_path)) {
  37.             return EXIT_FAILURE;
  38.         }
  39.         errno = 0;
  40.         fd = open(file_path, O_CREAT | O_WRONLY | O_EXCL, 0700);
  41.     } while(errno == EEXIST);
  42.     if (errno != 0) {
  43.         return EXIT_FAILURE;
  44.     }
  45.  
  46.     FILE *file = fdopen(fd, "w");
  47.     fprintf(file, pref_string);
  48.     for (int i = 1; i < argc; ++i) {
  49.         fprintf(file, "*%s\n", argv[i]);
  50.     }
  51.     fprintf(file, ")\nos.remove(\"%s\")", file_path);
  52.  
  53.     fclose(file);
  54.     close(fd);
  55.  
  56.     execlp(file_path, file_path, NULL);
  57.  
  58.     return EXIT_SUCCESS;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement