Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <dirent.h>
- #include <err.h>
- int semaphoreRead = -1;
- int semaphoreWrite = -1;
- void acquire() {
- if (write(semaphoreWrite, "a", 1) == -1) {
- err(1, "write");
- }
- }
- void release() {
- char buf;
- if (read(semaphoreRead, &buf, 1) == -1) {
- err(1, "read");
- }
- }
- void make(char *path);
- void watcher(char *executable) {
- char path[300];
- getcwd(path, 300);
- printf("path: %s\n", path);
- printf("watcher: %s\n", executable);
- pid_t pid = fork();
- if (pid == -1) {
- err(1, "fork");
- } else if (pid == 0) { // Child process
- char fullpath[400];
- snprintf(fullpath, sizeof(fullpath), "%s/%s", path, executable + 2);
- printf("fullpath: %s\n", fullpath);
- char* params[] = {executable, NULL};
- execvp("fullpath", &executable);
- err(1, "execp");
- } else { // Parent process
- int status;
- waitpid(pid, &status, 0);
- release();
- }
- }
- void traverse_directory(char *path) {
- DIR *dir = opendir(path);
- printf("dir: %s\n", path);
- if (dir == NULL) {
- err(1, "opendir");
- }
- struct dirent *entry;
- while ((entry = readdir(dir)) != NULL) {
- if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
- continue;
- }
- char full_path[PATH_MAX];
- snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
- printf("full_path: %s\n", full_path);
- if (entry->d_type == DT_DIR) { // If entry is a directory, recursively traverse it
- printf("full_path_dir: %s\n", full_path);
- traverse_directory(full_path);
- } else if (access(full_path, X_OK) == 0) { // If entry is executable, run watcher
- acquire();
- printf("full_path exec: %s\n", full_path);
- watcher(full_path);
- }
- }
- closedir(dir);
- }
- void make(char *path) {
- traverse_directory(path);
- while (semaphoreWrite > 0) {
- acquire();
- }
- }
- int main(int argc, char *argv[]) {
- if (argc != 2) {
- fprintf(stderr, "Usage: %s <max_parallelism>\n", argv[0]);
- exit(1);
- }
- int max_parallelism = atoi(argv[1]);
- if (max_parallelism <= 0) {
- fprintf(stderr, "Invalid argument: %s\n", argv[1]);
- exit(1);
- }
- // Create semaphore using a pipe
- int pipefd[2];
- if (pipe(pipefd) == -1) {
- err(1, "pipe");
- }
- semaphoreRead = pipefd[0]; // Use the read end of the pipe as the semaphore
- semaphoreWrite = pipefd[1];
- make(".");
- close(pipefd[0]);
- close(pipefd[1]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement