首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pause()是如何工作的?

pause()是如何工作的?
EN

Stack Overflow用户
提问于 2013-04-14 04:30:02
回答 1查看 25.8K关注 0票数 16

我对c完全是新手,我必须编写一个功能类似于pause()系统调用的函数mypause(),并在一个反复阻塞等待信号的程序中测试mypause()函数。te pause()函数是如何工作的?我不能像这样做一个mypause()吗:

代码语言:javascript
复制
fprintf( stderr, "press any key to continue\n" );

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-14 05:10:35

pause()函数会一直阻塞,直到有信号到达。用户输入不是信号。信号可以由另一个进程或系统本身发出。

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

为了在ISO C99中模拟pause的行为,你可以编写如下代码。代码已被注释,如果您对此实现有任何疑问,请提问。

代码语言:javascript
复制
#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);
}

注意:此示例仅适用于SIGINT信号。要处理额外的一组信号,可以使用具有不同信号号的其他signal()调用,或者使用带有引用所有所需信号的掩码的sigaction()

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

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15992574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档