Ignore <Ctrl-D>
Jonathan I. Kamens
jik at athena.mit.edu
Fri Mar 15 11:35:57 AEST 1991
In article <27DC2ABC.26018 at maccs.dcss.mcmaster.ca>, cui at maccs.dcss.mcmaster.ca (Jun Cui) writes:
|> I'm doing a menu in C, and trying to ignore <Ctrl-d> <Ctrl-c> <Ctrl-z> etc.
|> In other words, I would like the program not to be interrupted until user
|> select 'Quit' from the menu. (If I press <Ctrl-d> when the program is waiting
|> for user to select the menu, the program will go to infinite loop)
First of all, the reason the program you're writing goes into an infinite
loop is that you're getting EOF from stdin and your program isn't dealing with
it properly.
Most likely this is because you're assigning the return value of getchar to
a char (instead of to an int), so you don't notice when it returns EOF, since
EOF is a signed value and chars are often unsigned. Either that, or it's
because you're not checking for EOF at all. You should be.
Second, there are a few ways to disable ^D ^C ^Z etc. The first is to
change the special characters for the terminal (in order to disable those
characters). The second is to put the terminal into a mode that ignores those
characters. Check out the tty man page in section 4 of the manual (that's on
a BSD-like system; I don't know if it exists on SysV-like systems), or the
ioctl man page in section 2. The third is to install signal handlers for
SIGINT and SIGTSTP so that you can just ignore those signals -- when the user
types ^C or ^Z, your program doesn't actually get a ^C or ^Z character, it
gets a SIGINT or SIGTSTP signal.
Even if you change the special characters, or go into a different mode, or
install signal handlers for SIGINT and/or SIGTSTP, you still have to check for
EOF when reading from stdin.
By the way, it is generally considered anti-social to ignore ^Z, unless
you're doing something like writing a "secure program" that people aren't
supposed to be able to escape from. Your program should be smart enough to
suspend itself and start up again properly when the user continues it.
--
Jonathan Kamens USnail:
MIT Project Athena 11 Ashford Terrace
jik at Athena.MIT.EDU Allston, MA 02134
Office: 617-253-8085 Home: 617-782-0710
More information about the Comp.unix.programmer
mailing list