【问题标题】:Signal handling function + not ignoring SIGINT信号处理函数 + 不忽略 SIGINT
【发布时间】:2016-07-12 09:13:44
【问题描述】:

我必须编写一个程序来模拟 bash shell。程序的相关部分在这里。程序在收到 EOF(未显示)时终止。要实现的不同功能之一是在按下 CTRL-C 时不终止程序。如果收到 SIGINT,程序应该再次打印一个新的命令提示符。我有一个处理函数,它更改全局变量以结束当前循环迭代,以及一个外部循环,然后将再次更改它以重新进入内部循环。但是,当我按 CTRL-C 时,程序仍在退出。这是为什么呢?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<time.h>
#include<signal.h>
#include<sys/wait.h>

void SIGINT_handler(int signum);

static volatile sig_atomic_t endflag = 0;

int main(int argc, char **argv){

    while(1){
        endflag = 0;

        while(!endflag){

                  struct sigaction action;

                  action.sa_handler = &SIGINT_handler;
                  action.sa_flags = 0;

                  if((sigemptyset(&action.sa_mask) == -1)||(sigaction(SIGINT, &action, NULL) == -1)){
                           perror("Failed to set SIGINT handler");
                           exit(EXIT_FAILURE);
                 }
         }
    }

    return 0;
}

void SIGINT_handler(int signo){

    if(signo == SIGINT){
        endflag = 1;
    }
    fflush(stdout);

}

【问题讨论】:

  • 代码看起来或多或少没问题。在编译过程中是否收到任何警告?您使用的是哪个操作系统,哪个编译器?
  • 从信号句柄中刷新stdout 可能不是一个好主意。我也怀疑全局标志需要定义volatile
  • 您需要发布操作系统和编译器,这适用于带有 gcc 和 clang 的 Mac。
  • 我正在使用 Ubuntu 15.10 和 gcc 编译器。编译期间没有警告。
  • 在 Debian old-stable 上按预期工作。

标签: c signals posix


【解决方案1】:

你必须在主函数中注册信号处理函数

(void) 信号(SIGINT,SIGINT_handler);

进入主函数后

试试这个

int main(int argc, char **argv){

   (void) signal(SIGINT,SIGINT_handler);  

while(1){
    endflag = 0;

    while(!endflag){

              struct sigaction action;

              action.sa_handler = &SIGINT_handler;
              action.sa_flags = 0;

              if((sigemptyset(&action.sa_mask) == -1)||(sigaction(SIGINT, &action, NULL) == -1)){
                       perror("Failed to set SIGINT handler");
                       exit(EXIT_FAILURE);
             }
     }
}

return 0;

}

【讨论】:

  • sigaction()的调用也注册了一个信号处理程序。
猜你喜欢
  • 2014-08-20
  • 2012-10-08
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2013-09-04
相关资源
最近更新 更多