信号处理用C [英] Signal Handling in C

查看:174
本文介绍了信号处理用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何能实现信号处理为按Ctrl-C和Ctrl-D使用C ....所以,如果按Ctrl-C是pssed然后程序会忽略并再次尝试从用户输入$ P $ .. 。如果按Ctrl-D是pssed那么程序将终止$ p $ ...

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\n",msg); 
 }
}

谢谢,

戴夫

推荐答案

在与POSIX信号处理,您在您的处置两种手段。首先,最容易(但德precated)的方式,信号()。其次,更优雅,但当前复杂的方式,的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的手册解释了两者之间的差异,并给出很好的例子,美元如何使用这两个C $℃。它还列出了可以处理的信号,建议他们如何的处理,更在如何告诉任何给定的信号是如何(或者不是)深云目前的处理。这是多途径code比我要粘贴到一个答案在这里,因此链接。

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.

一旦您完成它的工作,你可能会觉得倾向于写了一个易于修改设置的函数来处理你的信号,并重新使用了code一遍又一遍。

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.

对不起,不给一个快速和肮脏code片段向您展示如何解决您的燃眉之急,但这不是一个快速和肮脏的话题:)

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆