SIGINT和SIGQUIT

时间:2014-11-05 00:17:59

标签: c terminal sigint

我想从我的代码启动计算器应用程序,用sigint-2中断它显示它已被中断,再次启动它,然后用sigquit-9退出它,想法是在C代码中中断它所以没有必要按ctrl-c或ctrl - \

  

编写一个C程序,通过signalfd文件描述符接受信号SIGINT和SIGQUIT。程序在接受SIGQUIT信号后终止。

1 个答案:

答案 0 :(得分:1)

我认为这可能就是你要找的东西

//
//  main.c
//  Project 4
//
//  Found help with understanding and coding at
// http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/
//

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
//signal handling function that will except ctrl-\ and ctrl-c
void sig_handler(int signo)
{
    //looks for ctrl-c which has a value of 2
    if (signo == SIGINT)
        printf("\nreceived SIGINT\n");
    //looks for ctrl-\ which has a value of 9
    else if (signo == SIGQUIT)
        printf("\nreceived SIGQUIT\n");
}

int main(void)
{
    //these if statement catch errors
    if (signal(SIGINT, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGINT\n");
    if (signal(SIGQUIT, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGQUIT\n");
    //Runs the program infinitely so we can continue to input signals
    while(1)
        sleep(1);
    return 0;
}