OiO.lk Blog C# What happens if fork() fails after some processes are created?
C#

What happens if fork() fails after some processes are created?


The goal of the code below is to create 4 subprocesses without generating any grandchildren. The code functions correctly if the fork function operates as expected. If fork fails while creating the first subprocess, the code will handle the failure appropriately.

However, I am curious about the case where 3 subprocesses are created, and then the fork fails when creating the fourth subprocess. In this case, if my understanding is correct, the parent process would exit, but the 3 already created subprocesses would still be running.

If so, how can I kil all created subprocesses before the parent process exits?

Edit: I am open to any suggestions to improve the code.

void create_subprocessies(int pids[], int pid_parent)
{
    for (int i = 0; i < 4; i++)
    {
        if (pid_parent != getppid())
        {
            if ((pids[i] = fork()) == -1)
            {
                perror("Fork");
                exit(-1);
            }
        }
    }
}



You need to sign in to view this answers

Exit mobile version