编写一个C程序,当按下Ctrl+C时不会终止

编写一个C程序,当按下Ctrl+C时不会终止。它打印一条消息“不能使用Ctrl+c终止”,并继续执行。

null

我们可以使用 C语言中的信号处理 为了这个。什么时候 Ctrl+C 按下后,生成SIGINT信号,我们可以捕获该信号并运行定义的信号处理程序。C标准在信号中定义了以下6个信号。h头文件。

SIGABRT–异常终止。 SIGFPE–浮点异常。 SIGILL–无效指令。 SIGINT–发送到程序的交互式注意请求。 SIGSEGV–无效的内存访问。 SIGTERM–发送给程序的终止请求。

附加信号被指定为Unix,类Unix操作系统(如Linux)定义了超过15个附加信号。看见 http://en.wikipedia.org/wiki/ Unix#U信号#POSIX#U信号 标准C库函数 信号() 可用于为上述任何信号设置处理程序。

/* A C program that does not terminate when Ctrl+C is pressed */
#include <stdio.h>
#include <signal.h>
/* Signal Handler for SIGINT */
void sigintHandler( int sig_num)
{
/* Reset handler to catch SIGINT next time.
signal (SIGINT, sigintHandler);
printf ( " Cannot be terminated using Ctrl+C " );
fflush (stdout);
}
int main ()
{
/* Set the SIGINT (Ctrl-C) signal handler to sigintHandler
signal (SIGINT, sigintHandler);
/* Infinite loop */
while (1)
{
}
return 0;
}


输出:按下Ctrl+C两次时

 
 Cannot be terminated using Ctrl+C
 
 Cannot be terminated using Ctrl+C

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享