HelloC/fork.c

91 lines
2.4 KiB
C

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <sys/wait.h>
#define LOOPS_PER_CHILD 2000
#define CHILDS 30
#define PIPE_READ 0
#define PIPE_WRITE 1
int main() {
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));
return 1;
} else if (pid == 0) {
// 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. 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
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;
fork();
fork();
fork();
printf("Hello World\n");
}