You are close but you are calling wait
in the child process when you should be calling waitpid
in the parent process. There is a nice explanation of this on wikipedia. I've modified your code below to use it.
void print_child_pid(int n) {
int i;
pid_t pid;
for (i = 1; i <= n; i++) {
pid = fork();
if (pid == -1) {
/* error handling here, if needed */
}
if (pid == 0) {
printf("child: process id = %d\n", getpid());
return;
}else{
int status;
(void)waitpid(pid, &status, 0);
}
}
}
Output with n = 4:
child: process id = 9363
child: process id = 9364
child: process id = 9365
child: process id = 9366