pause()如何工作?

Lui*_*ado 16 c

我在c中完全是菜鸟.我必须编写一个mypause()应具有与pause()系统调用类似的功能的函数,并mypause()在重复阻止等待信号的程序中测试该函数.te pause()功能如何工作?我不能这样做mypause():

fprintf( stderr, "press any key to continue\n" );
Run Code Online (Sandbox Code Playgroud)

为了让程序阻止并等待信号?

请记住,我不能使用pause()sigpause().

Hal*_*oum 14

pause()功能将阻塞,直到信号到达.用户输入不是信号.信号可以由另一个进程或系统本身发出.

Ctrl-C例如,按下会导致shell向SIGINT当前正在运行的进程发送信号,这在正常情况下会导致进程被终止.

为了模拟pauseISO C99中的行为,您可以编写如下内容.代码已注释,如果您对此实现有疑问,请询问.

#include <unistd.h>
#include <stdio.h>
#include <signal.h>

/**
 * The type sig_atomic_t is used in C99 to guarantee
 * that a variable can be accessed/modified in an atomic way
 * in the case an interruption (reception of a signal for example) happens.
 */
static volatile sig_atomic_t done_waiting = 0;

static void     handler()
{
  printf("Signal caught\n");
  done_waiting = 1;
}

void    my_pause()
{
  /**
   *  In ISO C, the signal system call is used
   *  to call a specific handler when a specified
   *  signal is received by the current process.
   *  In POSIX.1, it is encouraged to use the sigaction APIs.
   **/
  signal(SIGINT, handler);
  done_waiting = 0;
  while ( !done_waiting )
    ;
}

int     main()
{
  my_pause();
  printf("Hey ! The first call to my_pause returned !\n");
  my_pause();
  printf("The second call to my_pause returned !\n");
  return (0);
}
Run Code Online (Sandbox Code Playgroud)

请注意,此示例仅适用于SIGINT信号.要处理另一组信号,您可以使用signal()具有不同信号编号的其他呼叫,或使用sigaction()引用所有所需信号的掩码.

您可以在<signal.h>包含的系统中找到系统中可用信号的完整列表.

  • 忙碌等待很糟糕.在那个循环中睡一觉. (4认同)
  • @Halim坚持你的枪; 你的答案很好.忙碌的等待可能很难看,但技术上是正确的,也许是你在ISO C中可以做到的最好而不会触及POSIX.尝试在循环中做一些奇特的事情是程序员犯错误的经典场所. (3认同)