如何捕获 Control+D 信号? [英] How to capture Control+D signal?

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

问题描述

我想在我的程序中捕获 Ctrl+D 信号并为其编写信号处理程序.我怎样才能做到这一点?我正在使用 C 并使用 Linux 系统.

I want to capture the Ctrl+D signal in my program and write a signal handler for it. How can I do that? I am working on C and using a Linux system.

推荐答案

正如其他人已经说过的,要处理 Control+D,处理文件结尾".

As others have already said, to handle Control+D, handle "end of file"s.

Control+D 是用户和您视为标准输入的伪文件之间的一段通信.它并不特别意味着文件结束",而是更普遍的刷新我到目前为止输入的输入".刷新意味着程序中对 stdin 的任何 read() 调用都返回自上次刷新以来键入的输入的长度.如果该行非空,则尽管用户还没有键入return",但您的程序可以使用该输入.如果该行为空,则 read() 返回零,这被解释为文件结束".

Control+D is a piece of communication between the user and the pseudo-file that you see as stdin. It does not mean specifically "end of file", but more generally "flush the input I typed so far". Flushing means that any read() call on stdin in your program returns with the length of the input typed since the last flush. If the line is nonempty, the input becomes available to your program although the user did not type "return" yet. If the line is empty, then read() returns with zero, and that is interpreted as "end of file".

所以当使用 Control+D 结束一个程序时,它只在一行的开头起作用,或者如果你这样做两次(第一次刷新,read() 第二次返回零.

So when using Control+D to end a program, it only works at the beginning of a line, or if you do it twice (first time to flush, second time for read() to return zero).

试试看:

$ cat
foo
   (type Control-D once)
foofoo (read has returned "foo")
   (type Control-D again)
$

这篇关于如何捕获 Control+D 信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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