问题描述
我如何在 C 中实现 Ctrl-C 和 Ctrl-D 的信号处理....所以如果按下 Ctrl-C 那么程序将忽略并再次尝试从用户那里获取输入...如果 Ctrl-D 按下然后程序将终止...
How can I implement signal Handling for Ctrl-C and Ctrl-D in C....So If Ctrl-C is pressed then the program will ignore and try to get the input from the user again...If Ctrl-D is pressed then the program will terminate...
我的程序如下:
int main(){
char msg[400];
while(1){
printf("Enter: ");
fgets(msg,400,stdin);
printf("%s
",msg);
}
}
谢谢,
戴夫
推荐答案
在处理 POSIX 信号时,您可以使用两种方法.首先,简单(但已弃用)的方法,signal().其次,更优雅、当前但复杂的方式,sigaction().请使用 sigaction() ,除非您发现它在您需要工作的某些平台上不可用.
When dealing with POSIX signals, you have two means at your disposal. First, the easy (but deprecated) way, signal(). Second, the more elegant, current but complex way, sigaction(). Please use sigaction() unless you find that it isn't available on some platform that you need to work on.
本章解释了glibc手册的差异两者之间,并给出了关于如何使用两者的很好的示例代码.它还列出了可以处理的信号,建议如何处理应该,并更深入地了解如何判断任何给定的信号当前是(或不是)是> 处理.这比我想粘贴到这里的答案中的代码多得多,因此是链接.
This chapter of the glibc manual explains differences between the two and gives good example code on how to use both. It also lists the signals that can be handled, recommends how they should be handled and goes more in depth on how to tell how any given signal is (or is not) currently being handled. That's way more code than I'd want to paste into an answer here, hence the links.
花一两个小时阅读链接并完成示例确实值得.信号处理(尤其是在守护进程中)非常重要.一个好的程序应该处理所有可以处理的致命信号(即 SIGHUP)并明确忽略它可能不会使用的信号(即 SIGUSR1/SIGUSR2).
It really is worth the hour or two it would take you to read the links and work through the examples. Signal handling (especially in programs that daemonize) is extremely important. A good program should handle all fatal signals that can be handled (i.e. SIGHUP) and explicitly ignore signals that it might not be using (i.e. SIGUSR1 / SIGUSR2).
研究正常信号和实时信号之间的区别也没有什么坏处,至少要了解内核如何合并先验信号而不是后者.
It also won't hurt to study the difference between normal and real time signals, at least up to the understanding of how the kernel merges the prior and not the latter.
一旦您完成了它,您可能会倾向于编写一组易于修改的函数来处理您的信号并一遍又一遍地重用该代码.
Once you work through it, you'll probably feel inclined to write up an easy to modify set of functions to handle your signals and re-use that code over and over again.
很抱歉没有给出一个快速而肮脏的代码片段来向您展示如何解决您的紧迫需求,但这不是一个快速而肮脏的话题:)
Sorry for not giving a quick and dirty code snippet to show you how to solve your immediate need, but this isn't a quick and dirty topic :)
这篇关于C 中的信号处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!