Linux:将 sleep() 与信号结合起来

标签 linux signals sleep

你知道我在哪里可以看到不能与 sleep() 命令一起使用的信号和函数列表吗?

例如,你可以看到这段代码:

// this program presents how to block signal SIGINT
// while running in critical region
#include    <signal.h>
#include        <stdio.h>
#include        <unistd.h>
#include        <stdlib.h>
#include        <stdio.h>

static void sig_int(int);

int main(void)  //6
{
  sigset_t  newmask, oldmask, zeromask;

  if (signal(SIGINT, sig_int) == SIG_ERR)
    fprintf(stderr,"signal(SIGINT) error");

  sigemptyset(&zeromask);

  sigemptyset(&newmask);
  sigaddset(&newmask, SIGINT);

  /* block SIGINT and save current signal mask */
  if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
    fprintf(stderr,"SIG_BLOCK error");

  /* critical region of code */
  printf("In critical region: SIGINT will be blocked for 3 sec.\n");
  printf("Type Ctrl-C in first 3 secs and see what happens.\n");
  printf("Then run this program again and type Ctrl-C when 3 secs elapsed.\n");
  fflush(stdout);


  sleep(3);

  printf("end sleep");
  /* allow all signals and pause */
  if (sigsuspend(&zeromask) != -1)
    fprintf(stderr,"sigsuspend error");

  printf("after return from sigsuspend: ");

  /* reset signal mask which unblocks SIGINT */
  if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
    fprintf(stderr,"SIG_SETMASK error");

  /* and continue processing ... */
  exit(0);
}

static void sig_int(int signo)
{
  printf("\nIn sig_int: SIGINT\n"); fflush(stdout);
  return;
}

程序不会在 sleep() 之后唤醒。你知道为什么吗?

最佳答案

如果你使用strace,你可以看到你的程序实际做了什么

strace ./我的签名程序

如果 sleep 永远不会返回,我猜任务已经收到一个 SIGSTOP(这个不能被拦截)或 SIGTSTP(这个你可以用信号处理程序拦截),导致操作系统停止整个过程,直到一个 SIGCONT收到了。

关于Linux:将 sleep() 与信号结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36700990/

相关文章:

c# - 有没有办法唤醒 sleep 线程?

linux - 如何删除 "cargo new"创建的项目目录

PHP 执行 mocp 命令

c++ - 抓还是不抓

c - C中具有多个警报的多个线程

java - 如何在 NetBeans SWING 内的循环中使用 Thread.sleep?

linux - 如何用erlang搭建TCP服务器?

linux - 有没有办法将文件描述符传递给另一个进程?

c - 如何不在我的 shell 上显示信号?

c# - Windows 服务 OnPowerEvent