'Handler callback is not cliing properly in Signals for SIGCHLD

I registered handler for SIGCHLD stop/exit and i am creating 4 child i am modifying global variable in it works fine as copy on write(COW). But handler function is not called for 4 child. when i print the global variable in parent, its value is 18 as i am expecting 21.

[Attached the output of image] [1]: https://i.stack.imgur.com/7QOze.png

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/wait.h>


#define N 4
int val = 9;
void handler(int sig)
{
    val += 3;
    printf("Inside handler getpid() = %d    val = %d\n", getpid(), val);
    return;
}
int main()
{
    pid_t pid;
    int i;
    signal(SIGCHLD, handler);
    for (i = 0; i < N; i++)
    {
        if ((pid = fork()) == 0)
        {
            val -= 3;
            printf("Inside child getpid() = %d    val = %d\n", getpid(), val);
            exit(0);
        }
    }

    for (i = 0; i < N; i++)
    {
        waitpid(-1, NULL, 0);
        //printf("Inside parent getpid() = %d    val = %d\n", getpid(), val);
    }
    printf("val = %d\n", val);
}


Sources

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

Source: Stack Overflow

Solution Source