Hello, Im a beginner in C and I’ve started learning about system calls and forking. I am forking in a loop but I get unexpected behaviour. My program takes one number and simply forks(), it also prints pids using getppid and pid:
Code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
int i;
int n;
int kids;
if (argc != 2) {
fprintf(stderr, "error");
exit(1);
}
kids = strtol(argv[1], NULL, 10);
for (i = 0; i < kids; i++) {
n = fork();
if (n < 0) {
perror("fork");
exit(1);
}
printf("pid = %d, ppid = %d, i = %d\n", getpid(), getppid(), i);
exit(0);
}
return 0;
}
when running this program with ANY command line the output is:
Code:
$ ./my_program 3
pid = 7824, ppid = 7763, i=0
pid = 7825, ppid = 7824, i=0
My goal is to make sure the children dont fork, only the parent should fork. W Other sources also say to exit the loop in this way, and i cant exit any further up as i want my children to print the pid’s too. I expected 6 lines since I passed in 3, but with any argument I get the same thing. What mistake am I making?
Thank you for your help!