0

How to detect if user press [control + D]

I m writing a shell. The shell has to print " > " all over the time.
I m trying to implement a new command -> [control + d]
When the user press [control] buttom [+]and [D]buttom
The shell should quit

Here is the sudo code

int user_press_control_D = 0;
while(user_press_control_D == 0){
  running();
  detect(user_input);
  if user_input == (Control + D){
  user_press_control_D = 1; //quit 
  }
}

How to actually write / detect / check that user press (Control + D)

Chener Zhang
  • 129
  • 9
  • Ctrl + D is a Unicode U+0004 or ascii “4” valued code character. You can scan your shell input for an EOT character by above value. Don’t know is this a best approach though. – user14063792468 Oct 05 '19 at 19:57
  • 1
    When you are doing normal input from a terminal in Unix, the program reading the input does not receive a control-D character when the user presses control-D. Instead, control-D is used to signal “send input immediately,” and [this also causes it to act like an end-of-file](https://stackoverflow.com/a/21365313/298225). You may want to design your shell to work with this normal method: When it attempts to read a character from the terminal and gets a “no character available” indication, treat it as if the end of input has been reached. – Eric Postpischil Oct 05 '19 at 20:08
  • 1
    On the other hand, if you really want to receive a control-D when the user types control-D, you have to change the mode of terminal input management. – Eric Postpischil Oct 05 '19 at 20:09

1 Answers1

-1

Trap command should do the job.

Tweaking code to capture EOF(ctrl+d) and trap the signal

trap 'echo "ctrl+d pressed"' 0 trap '' 2

while read data; do echo "do your job" done

Abhishek Mishra
  • 111
  • 1
  • 10