如何离开(中断)waitpid()函数?

时间:2018-05-19 13:31:18

标签: c shell unix wait waitpid

目前我正在编写一个shell,我使用waitpid()函数来处理我的子进程。

我还安装了一个信号处理程序,因此我可以捕获SIGINT( CTRL + C )信号。

所以我现在想要的是当有人按下SIGINT( CTRL + C )信号时,它应该离开waitpid()函数并保持正常运行。

我正在寻找可以帮助我的功能。

2 个答案:

答案 0 :(得分:0)

安装信号处理程序,不用 SA_RESTART标志:

void handler( int sig, siginfo_t *si, void *arg )
{
    ...
}

...

struct sigaction newact;
memset( &newact, 0, sizeof( newact ) );
sigemptyset( &newact.sa_mask );
newact.sa_flags = SA_SIGINFO;  // note that **lack** of SA_RESTART
newact.sa_siginfo = handler;

sigaction( SIGINT, &newact, NULL );

您必须为此添加错误检查,并注意您现在必须处理代码中的中断调用。

答案 1 :(得分:0)

waitpid()上的进程阻止会在收到信号时返回,并将errno设置为EINTR

为了使信号处理程序工作,我没有使用选项SA_RESTART安装。

要安装信号手柄而不设置选项SA_RESTART,首选功能为sigaction()

void handle(int sig)
{
  /* Do nothing. */
}

int main(void)
{
  sigaction(SIGINT, (struct sigaction){handler}, NULL);

  /* fork and bla ... */

  if (-1 == waitpid(..., /*no WNOHANG here */))
  {
    if (EINTR == errno)
    {
      /* process received signal */
      ...