Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <dirent.h>
- #include <string.h>
- #include <signal.h>
- #include <stdbool.h>
- #include <sys/wait.h>
- #define BUF_SIZE (1 << 10)
- bool done = false;
- void SIGUSR2Handler(int sig) {
- done = true;
- }
- void iterDir(const char path[], int pipefd) {
- DIR *dir = opendir(path);
- if (dir == NULL) {
- perror("opendir");
- exit(1);
- }
- for (struct dirent *de; (de = readdir(dir));) {
- if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
- continue;
- }
- char absPath[BUF_SIZE];
- sprintf(absPath, "%s/%s", path, de->d_name);
- struct stat statBuff;
- if (stat(absPath, &statBuff)) {
- perror("stat");
- exit(1);
- }
- if (S_ISREG(statBuff.st_mode)) {
- int filePipe[2];
- if (pipe(filePipe)) {
- perror("pipe");
- exit(1);
- }
- pid_t pid = fork();
- if (pid == -1) {
- perror("fork");
- exit(1);
- }
- if (pid == 0) {
- close(filePipe[0]);
- if (dup2(filePipe[1], STDOUT_FILENO) == -1) {
- perror("dup2");
- exit(1);
- }
- execlp("wc", "wc", "-c", absPath, (char *)NULL);
- perror("execlp");
- exit(1);
- }
- close(filePipe[1]);
- FILE *f = fdopen(filePipe[0], "r");
- if (f == NULL) {
- perror("fdopen");
- exit(1);
- }
- int fileSize;
- fscanf(f, "%d", &fileSize);
- write(pipefd, &fileSize, sizeof(fileSize));
- fclose(f);
- } else if (S_ISDIR(statBuff.st_mode)) {
- iterDir(absPath, pipefd);
- }
- }
- if (closedir(dir)) {
- perror("closedir");
- }
- }
- int main(int argc, char *argv[]) {
- if (argc != 2) {
- fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
- exit(1);
- }
- struct sigaction sa;
- memset(&sa, 0, sizeof(struct sigaction));
- sa.sa_handler = SIGUSR2Handler;
- if (sigaction(SIGUSR2, &sa, NULL) == -1) {
- perror("sigaction");
- exit(1);
- }
- int pipefd[2];
- if (pipe(pipefd) == -1) {
- perror("pipe");
- exit(1);
- }
- pid_t concentratorPid = fork();
- if (concentratorPid == -1) {
- perror("fork");
- exit(1);
- }
- if (concentratorPid == 0) {
- close(pipefd[1]);
- int totalSize = 0;
- int fileSize;
- while (read(pipefd[0], &fileSize, sizeof(fileSize)) > 0) {
- totalSize += fileSize;
- }
- close(pipefd[0]);
- printf("Total size: %d\n", totalSize);
- exit(0);
- }
- close(pipefd[0]);
- while (!done) {
- printf("WAIT\n");
- sleep(1);
- }
- iterDir(argv[1], pipefd[1]);
- close(pipefd[1]);
- // Wait for all child processes to finish
- int ws;
- pid_t cp;
- while ((cp = wait(&ws)) > 0) {
- if (WIFEXITED(ws)) {
- printf("Child %d finished with code %d!\n", cp, WEXITSTATUS(ws));
- } else {
- puts("Child has been brutally murdered!");
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement