HelloC/fork.c

42 lines
1018 B
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
int main() {
for (int start = 0; start < LOOPS_PER_CHILD * CHILDS; start += LOOPS_PER_CHILD) {
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();
for (int i = start; i < start + LOOPS_PER_CHILD; i++) {
fprintf(stdout, "%d: %d\n", childPid, i);
fflush(stdout);
}
printf("Fork %d finished counting from %d\n", childPid, start);
return 0;
} else {
printf("Fork %d successfull\n", pid);
}
}
// wait for all childs to terminate
while (wait(NULL) > -1);
return 0;
fork();
fork();
fork();
printf("Hello World\n");
}