From 076e324e52881ec7f9ed5a7822d47b441b29f9a6 Mon Sep 17 00:00:00 2001 From: damage Date: Tue, 27 Aug 2024 21:52:38 +0200 Subject: [PATCH] use pipes to write back from child to parent --- fork.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/fork.c b/fork.c index 9220505..60dc321 100644 --- a/fork.c +++ b/fork.c @@ -8,8 +8,19 @@ #define LOOPS_PER_CHILD 2000 #define CHILDS 30 +#define PIPE_READ 0 +#define PIPE_WRITE 1 + int main() { - for (int start = 0; start < LOOPS_PER_CHILD * CHILDS; start += LOOPS_PER_CHILD) { + int pipes[CHILDS][2]; + pid_t childToPipes[CHILDS]; + + for (int child = 0; child < CHILDS; child++) { + if (pipe(pipes[child]) == -1) { + fprintf(stderr, "Error creating pipe for child %d: %s\n", child, strerror(errno)); + return 2; + } + pid_t pid = fork(); if (pid == -1) { fprintf(stderr, "Error forking: %s\n", strerror(errno)); @@ -18,19 +29,57 @@ int main() { // I AM FORK! pid_t childPid = getpid(); + // close read of pipe + close(pipes[child][PIPE_READ]); + + int start = child * LOOPS_PER_CHILD; + long sum = 0; for (int i = start; i < start + LOOPS_PER_CHILD; i++) { fprintf(stdout, "%d: %d\n", childPid, i); fflush(stdout); + sum += i; } - printf("Fork %d finished counting from %d\n", childPid, start); + + printf("Fork %d finished counting from %d. Sum is %d\n", childPid, start, sum); + + if (write(pipes[child][PIPE_WRITE], &sum, sizeof(sum)) == -1) { + fprintf(stderr, "Error writing pipe for child %d: %s\n", child, strerror(errno)); + return 4; + } + + close(pipes[child][PIPE_WRITE]); + return 0; } else { + // close write of pipe + close(pipes[child][PIPE_WRITE]); + childToPipes[child] = pid; printf("Fork %d successfull\n", pid); } } // wait for all childs to terminate - while (wait(NULL) > -1); + pid_t childPid; + long overallSum = 0; + while ((childPid = wait(NULL)) != -1) { + printf("Child %d terminated\n", childPid); + long sum = -1; + for (int child = 0; child < CHILDS && sum == -1; child++) { + if (childToPipes[child] == childPid) { + read(pipes[child][PIPE_READ], &sum, sizeof(sum)); + close(pipes[child][PIPE_READ]); + } + } + + if (sum != -1) { + overallSum += sum; + } else { + fprintf(stderr, "Error reading from pipe\n"); + return 3; + } + } + + printf("Overall Sum: %d\n", overallSum); return 0;