0

我正在尝试创建 4 个子进程,直到孩子死,父母应该等待。我写了一个程序,但是当我运行这段代码时,十分之一,它无法从每个孩子那里捕获 SIGCHLD,然后我的程序进入无限循环。它发生真的很少,但仍然..

你能告诉我为什么以及如何解决它吗?

这是我的代码。

sig_atomic_t child_exit_status;
sig_atomic_t child_numbers = 0;

void clean_up(int signal_number, siginfo_t * info, void* context)
{
    //printf("SIGCHILD from %d calling\n", info->si_pid);
    waitpid(info->si_pid, &child_exit_status, 0);
    child_numbers++;
}


int main(int argc, char **argv)
{
    // SIGCHLD catcher 
    struct sigaction sigchld_action;
    memset(&sigchld_action, 0, sizeof(sigchld_action));
    sigchld_action.sa_sigaction = &clean_up;
    sigchld_action.sa_flags = SA_SIGINFO;
    sigaction(SIGCHLD, &sigchld_action, NULL);


    int pid1, pid2, pid3, pid4;


    printf("pid : %d\n", getpid());

    pid1 = fork();
    //child1
    if(pid1 == 0)
    {
        printf("child1 %d, parent %d\n", getpid(), getppid());
    }
    else
    {
        pid2 = fork();
        //child2
        if(pid2 == 0)
        {
            printf("child2 %d, parent %d\n", getpid(), getppid());
        }
        else
        {
            pid3 = fork();
            //child3
            if(pid3 == 0)
            {
                printf("child3 %d, parent %d\n", getpid(), getppid());
            }
            else
            {
                pid4 = fork();
                //child4
                if(pid4 == 0)
                {
                    printf("child4 %d, parent %d\n", getpid(), getppid());
                }
                else
                {
                    while(child_numbers < 4)
                    {

                    }
                    printf("i got the signals.");
                }

            }

        }

    }



    return 0;
}

我尝试了一些新的东西,但它也不起作用..

void clean_up(int signal_number, siginfo_t * info, void* context)
{
    printf("SIGCHILD from %d calling\n", info->si_pid);
    while (1)
    {
        int status;
        pid_t pid = waitpid(-1, &status, WNOHANG);
        if (pid <= 0) 
        {
            break;
        }
        else
        {
            waitpid(pid, &status, 0);
            break;
        }
    }
    child_numbers++;
}

4

0 回答 0