Determine pid of terminated process

萝らか妹 提交于 2019-12-18 13:25:50

问题


I'm trying to figure out what the pid is of a process that sent the SIGCHLD signal, and I want to do this in a signal handler I created for SIGCHLD. How would I do this? I'm trying:

int pid = waitpid(-1, NULL, WNOHANG);

because I want to wait for any child process that is spawned.


回答1:


If you use waitpid() more or less as shown, you will be told the PID of one of the child processes that has died — usually that will be the only process that has died, but if you get a flurry of them, you might get one signal and many corpses to collect. So, use:

void sigchld_handler(int signum)
{
    pid_t pid;
    int   status;
    while ((pid = waitpid(-1, &status, WNOHANG)) != -1)
    {
        unregister_child(pid, status);   // Or whatever you need to do with the PID
    }
}

You can replace &status with NULL if you don't care about the exit status of the child.



来源:https://stackoverflow.com/questions/2595503/determine-pid-of-terminated-process

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