'waiting once after sending kill signal to multiple processes?

So I'm working on a project for one of my programming classes, and part of this assignment is about being able to launch process in the background, and being able to kill them when the user types "endb".

In order to kill the background processes, I have an array (PIDpool) which holds the PIDs of all the processes, and whenever the user input "endb", I go through this array of PIDs and kill them one by one.

Though, in order for this to work, I had to add a single wait after I sent a kill signal to each process. If I didn't, there would be a single defunct process left, and if I put a wait for each kill signal (by putting the wait within the killing loop), the program would hang.

While I'm happy to know my program seems to be working, I'm wondering why that wait is necessary, cuz it would seem to me that I would need either to wait for each process after killing them or wait for none at all...

Thanks in advance ^^

static void backgroundExecution(char** cmd_tokens){
    if(!strcmp(cmd_tokens[0], "endb")){
        for(size_t i = 0; i < arraySize(PIDpool); i++){
            intptr_t PID = (intptr_t) arrayGet(PIDpool, i);
            kill(PID, SIGKILL);
        }
        wait(NULL);   // <------------ THIS WAIT HERE
        arrayEmpty(PIDpool);
    }else{
        pid_t PID = fork();
        if(PID == 0){
            execvp(cmd_tokens[0], cmd_tokens);
        }else{
            arrayPushBack(PIDpool, (void*) (unsigned long) PID);
        }
    }
}


Solution 1:[1]

Look deeper into wait() and waitpid(). Wait simply waits for any child process to terminate, thus it works in your case.
You actually don't check whether each process has indeed stopped, nor whether the kill function returned an error.
As pointed out in the comments, your cast to intptr_t is incorrect, not sure what the type of PIDpool is but it should look like pid_t PIDpool[POOL_SIZE];

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 BG_Cw