HelloC/fork.c

42 lines
1018 B
C
Raw Normal View History

2024-08-26 22:00:11 +02:00
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
2024-08-27 20:14:04 +02:00
#include <sys/wait.h>
#define LOOPS_PER_CHILD 2000
#define CHILDS 30
2024-08-26 22:00:11 +02:00
int main() {
2024-08-27 20:14:04 +02:00
for (int start = 0; start < LOOPS_PER_CHILD * CHILDS; start += LOOPS_PER_CHILD) {
2024-08-26 22:00:11 +02:00
pid_t pid = fork();
if (pid == -1) {
fprintf(stderr, "Error forking: %s\n", strerror(errno));
return 1;
} else if (pid == 0) {
// I AM FORK!
2024-08-27 20:14:04 +02:00
pid_t childPid = getpid();
for (int i = start; i < start + LOOPS_PER_CHILD; i++) {
fprintf(stdout, "%d: %d\n", childPid, i);
fflush(stdout);
2024-08-26 22:00:11 +02:00
}
2024-08-27 20:14:04 +02:00
printf("Fork %d finished counting from %d\n", childPid, start);
2024-08-26 22:00:11 +02:00
return 0;
} else {
printf("Fork %d successfull\n", pid);
}
}
2024-08-27 20:14:04 +02:00
// wait for all childs to terminate
while (wait(NULL) > -1);
return 0;
2024-08-26 22:00:11 +02:00
fork();
fork();
fork();
printf("Hello World\n");
}