c - 暂停()如何工作?

标签 c

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

fprintf( stderr, "press any key to continue\n" );

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

请记住,我永远无法使用 pause()sigpause()

最佳答案

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

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

为了模仿 pause 的行为在 ISO 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);
}

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

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

关于c - 暂停()如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15992574/

相关文章:

c - fork() 在 gcc 编译器中如何运行?

c - 在同一行而不是新行上更新 printf 值

c - 如何在 Linux 上将文件读入 C 程序?

c - 如何生成一个在 c 中依次运行多个程序的 makefile?

c - 如何根据输入数量定义数组大小?

c - 在 c 和正则表达式中使用 flex

C套接字编程通过同一连接发送多个发送和接收

c++ - 替换文件中的单词

c - C语言更新表格格式

c - C语言程序输出中的指针