0

I'm trying to execute and schedule my own list of processes read from a file. The files are running in a random order and I'm just curious as to why this is happening. I have simple print statements in the first, second, etc files that tell which is running, and they always print in different (seemingly random) orders. It isn't messing up my functionality thus far, I'm just curious why this is.

main.c below

int main(int argc, char ** argv) {
    pid_t pid[50];
    pid_t wpid;
    int i, j;
    int status = 0;
    char *newenvp[] = {NULL};
    char *newargv[] = {"./files.txt", NULL};

    printf("Before forking in the parent\n");
    int numProgs = readPrograms();

    for (i=0; i<numProgs; i++) {
        pid[i] = fork();
        if (pid[i] < 0) {
            perror("fork error");
            exit(EXIT_FAILURE);
        }
        else if (pid[i] == 0) {
            printf("Child process running\n");
            execve(programs[i], newargv, newenvp);
            perror("execve error");
            exit(EXIT_FAILURE);
        }
    }
    for (i=0; i<numProgs; i++) {
        wait(&status);
    }
    return 0;
}
char* programs[50];
int readPrograms();

readPrograms.c below

int readPrograms() {
    int i=0;
    char line[50];
    int numProgs = -1;

    FILE *file;
    file = fopen("files.txt", "r");

    while(fgets(line, sizeof(line), file)!=NULL) {
        line[strlen(line)-1] = '\0';
        programs[i]=strdup(line);
        i++;
        numProgs++;
    }
    fclose(file);
    return numProgs;
}

files.txt below

./first
./second
./third
./fourth
user3192682
  • 123
  • 1
  • 2
  • 11

1 Answers1

0

When calling fork, your system creates the new process (copy itself,call exec,overlay itself). Then your fork is ready, both the parent and the child process are marked ready and the running order of the processes is chosen by your system-scheduler. So depending on your scheduler either your parent or your child is now run.