Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <dirent.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <string.h>
- #include <fcntl.h>
- #include <sys/wait.h>
- #include <err.h>
- #define MAX_PATH_LENGTH 1024
- int pipefd[2];
- void explore_and_execute(const char *dirpath) {
- DIR *dir;
- struct dirent *entry;
- char path[MAX_PATH_LENGTH];
- struct stat statbuf;
- int active_processes = 0;
- if (!(dir = opendir(dirpath)))
- return;
- while ((entry = readdir(dir)) != NULL) {
- if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
- continue;
- sprintf(path, "%s/%s", dirpath, entry->d_name);
- if (stat(path, &statbuf) == -1)
- continue;
- if (S_ISDIR(statbuf.st_mode)) {
- char dummy;
- read(pipefd[0], &dummy, 1);
- pid_t pid = fork();
- if (pid == 0) {
- explore_and_execute(path);
- exit(0);
- } else if (pid > 0) {
- active_processes++;
- write(pipefd[1], &dummy, 1);
- }
- } else if (S_ISREG(statbuf.st_mode) && (statbuf.st_mode & S_IXUSR)) {
- char dummy;
- if (read(pipefd[0], &dummy, 1) != 1) {
- err(1, "read from pipe");
- }
- pid_t pid = fork();
- if (pid < 0) {
- err(1, "fork");
- } else if (pid == 0) {
- execl(path, path, (char *)NULL);
- err(1, "execl");
- }
- wait(NULL);
- if (write(pipefd[1], &dummy, 1) != 1) {
- err(1, "write to pipe");
- }
- }
- }
- while (active_processes > 0) {
- wait(NULL);
- active_processes--;
- }
- closedir(dir);
- }
- void check_pipe(int limit_) {
- for(int i = 0; i < limit_; i++) if(write(pipefd[1], "1", 1) != 1) err(1, "initialize error");
- }
- int main(int argc, char *argv[]) {
- int k = atoi(argv[1]);
- pipe(pipefd);
- check_pipe(k);
- explore_and_execute(".");
- close(pipefd[0]);
- close(pipefd[1]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement