'For loop is executing in wrong order

I am doing a for loop to create children with fork and print their pids, but instead of printing them in order it mixes them up.! what it prints :

[PARENT/PID=953] Created child 0 [PID=954] and initial state f

[PARENT/PID=953] Created child 3 [PID=957] and initial state f

[PARENT/PID=953] Created child 2 [PID=956] and initial state t

[PARENT/PID=953] Created child 1 [PID=955] and initial state f

also prints in other orders

tried to put wait(&status) in different places but it didnt help.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define PERMS 0644
int main(int argc, char **argv) {
int n = strlen (argv[1]);
int status;
    for(int i=0;i<n;i++) // loop will run n times
    {
        if(fork() == 0)
        {
            char s[5];
            sprintf(s, "%c", argv[1][i]);
            char *const argv2[] = {"./child.c",s,NULL};
            wait(&status);
            status = execv("./child", argv2);    
            printf("[PARENT/PID=%d] Created child %d [PID=%d] and initial state %s \n",getppid(),i,getpid(),s);
            exit(0);
        }
    }
    for(int i=0;i<n;i++) // loop will run n times
    wait(NULL);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source