Handling SIGCHLD, how to record the return values of children as they die

为君一笑 提交于 2019-11-30 16:09:55

问题


void childSignalHandler(int signo) {
    int status;

    pid_t pid = wait(&status);

    struct PIDList* record = getRecordForPID(childlist, pid);
    if (record != NULL)
        record->returnValue = status;
}

Quick question:

I want this handler to, when a child dies (this app spawns lots of children), get their return value and record it (last three lines). Will this do it, or am I getting all this API business wrong?

Thank you for your time!

(also, linux API terminology is creepy as hell, check for dying children and whatnot)


回答1:


This should do the job, if you set your function as a handler for SIGCHLD.

However, SIGCHLD can be send to parent process not only after the child exited. Some other events are signaled this way as well (for instance when the child is stopped). See man wait(3) for detailed explanation.




回答2:


Note signals are not queued. If two children die in quick succession, you may only recieve one SIGCHLD. So, you should actually loop around calling waitpid() until there are no more exiting processes to handle:

int status;
pid_t pid;

while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
    if (WIFEXITED(status)) {
        struct PIDList *record = getRecordForPID(childlist, pid);

        if (record != NULL)
            record->returnValue = WEXITSTATUS(status);
    }
}


来源:https://stackoverflow.com/questions/5530904/handling-sigchld-how-to-record-the-return-values-of-children-as-they-die

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!