Advertisement
keker123

Untitled

May 12th, 2024
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <dirent.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <string.h>
  8. #include <fcntl.h>
  9. #include <sys/wait.h>
  10. #include <err.h>
  11.  
  12. #define MAX_PATH_LENGTH 1024
  13.  
  14. int pipefd[2];
  15.  
  16. void explore_and_execute(const char *dirpath) {
  17.     DIR *dir;
  18.     struct dirent *entry;
  19.     char path[MAX_PATH_LENGTH];
  20.     struct stat statbuf;
  21.     int active_processes = 0;
  22.  
  23.     if (!(dir = opendir(dirpath)))
  24.         return;
  25.  
  26.     while ((entry = readdir(dir)) != NULL) {
  27.         if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
  28.             continue;
  29.  
  30.         sprintf(path, "%s/%s", dirpath, entry->d_name);
  31.         if (stat(path, &statbuf) == -1)
  32.             continue;
  33.  
  34.         if (S_ISDIR(statbuf.st_mode)) {
  35.             char dummy;
  36.             read(pipefd[0], &dummy, 1);
  37.             pid_t pid = fork();
  38.             if (pid == 0) {
  39.                 explore_and_execute(path);
  40.                 exit(0);
  41.             } else if (pid > 0) {
  42.                 active_processes++;
  43.                 write(pipefd[1], &dummy, 1);
  44.             }
  45.         } else if (S_ISREG(statbuf.st_mode) && (statbuf.st_mode & S_IXUSR)) {
  46.             char dummy;
  47.             if (read(pipefd[0], &dummy, 1) != 1) {
  48.                 err(1, "read from pipe");
  49.             }
  50.             pid_t pid = fork();
  51.             if (pid < 0) {
  52.                 err(1, "fork");
  53.             } else if (pid == 0) {
  54.                 execl(path, path, (char *)NULL);
  55.                 err(1, "execl");
  56.             }
  57.             wait(NULL);
  58.             if (write(pipefd[1], &dummy, 1) != 1) {
  59.                 err(1, "write to pipe");
  60.             }
  61.         }
  62.     }
  63.     while (active_processes > 0) {
  64.         wait(NULL);
  65.         active_processes--;
  66.     }
  67.     closedir(dir);
  68. }
  69.  
  70. void check_pipe(int limit_) {
  71.     for(int i = 0; i < limit_; i++) if(write(pipefd[1], "1", 1) != 1) err(1, "initialize error");
  72. }
  73.  
  74. int main(int argc, char *argv[]) {
  75.     int k = atoi(argv[1]);
  76.     pipe(pipefd);
  77.     check_pipe(k);
  78.  
  79.     explore_and_execute(".");
  80.  
  81.     close(pipefd[0]);
  82.     close(pipefd[1]);
  83.  
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement