Signal handler and waitpid coexisting

南楼画角 提交于 2019-12-13 01:16:02

问题


I'm coding a shell in C that should support background and foreground processes.

Constraints:

  • Background processes that terminate should be caught by signal handler
  • No global variables can be used for communicating from signal handler
  • No list of processes/pids allowed

My solution:

  • Waitpid until foreground process terminates
  • For background processes, immediately return to prompt
  • Handler catches SIGCHLD where waitpid is used to clear process table

Problem:

  • Foreground processes also trig handler causing one of two waitpids to error
  • Can't solve by ignoring SIGCHLD while running foreground process, since background process might terminate during that time
  • Can't find a way to make handler ignore specific pid (the foreground process started)

Thanks!


回答1:


Problem:

  • Foreground processes also trig handler causing one of two waitpids to error

This is not a problem - just leave the handler then.

void handler(int signum)
{
    pid_t pid;
    while (pid = waitpid(-1, NULL, WNOHANG), pid > 0)
        fprintf(stderr, "%d terminated\n", pid);
}


来源:https://stackoverflow.com/questions/29657624/signal-handler-and-waitpid-coexisting

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