I wrote a program that creates multiple processes with fork(). Now I'm trying to make it so that each time I call fork(), only the original parent process produces children. For instance, if I give an argument of 4, I should have all 4 ppid's be the same and its children.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
int main(int argc, char **argv) {
int i;
int n;
int num_kids;
if(argc != 2) {
fprintf(stderr, "Usage: forkloop <numkids>\n");
exit(1);
}
num_kids = atoi(argv[1]);
for(i = 0; i < num_kids; i++) {
n = fork();
if(n < 0) {
perror("fork");
exit(1);
} else if (n == 0) {
exit(i);
}
printf("pid = %d, ppid = %d, i = %d\n", getpid(), getppid(), i);
}
return 0;
}
When I run this, each ppid is the same but each child pid is the same as well. If I give in 4 as my argument, I get:
pid = 19765, ppid = 18449, i = 0
pid = 19765, ppid = 18449, i = 1
pid = 19765, ppid = 18449, i = 2
pid = 19765, ppid = 18449, i = 3
Should the child pid's all be the same, or is there something wrong with my code?