Search code examples
cprocessforkwait

Which child will execute first when you call fork() and wait() multiple times?


When you call fork() multiple times, and then call wait(); which child will be executed first? The first, or second child?

int main(int ac, char **av, char **env)
{
    t_d f;
    static int ii;
    int fd[2];
    int pid;
    int pid1;

    if (ac != 5)
        return (1);
    else
    {
        // f.fd1 = creat_open_file(av[1], 0);
        // f.fd2 = creat_open_file(av[4], 1);
        if (pipe(fd) == -1)
            exit (1);
        pid = fork();
        if (pid == -1)
            exit (1);
        if (pid == 0)
        {
            ft_printf("chi i == %d\n", ii++);
            child_process_(av[2], env, fd);
        }
        pid1 = fork();
        if (pid1 == 0)
        {
            ft_printf("par i == %d\n", ii++);
            parent_process_(av[3], env, fd);
        }
        // waitpid(pid, NULL, 0);
        // waitpid(pid1, NULL, 0);
        close(fd[1]);
        close(fd[0]);
        wait(NULL);
        wait(NULL);
    }
    return (0);
}

In my code, the first child is executed first, but I want to know the details as to why the first is who is executed first and not the second child.

For my expecting, I think the second child is who needs to be executed first.


Solution

  • It doesn't have a fixed order of operation, the reason the first child is more likely going to be executed before the second child is just because it was created first and probably requested cpu time before the 2nd one. In the way your code is structured all childs will execute lines of code outside of the if because you're not exiting so the first child process will actually call fork and both will call wait(NULL) 2 times, including the parent process. Be careful with that.