user15775871
user15775871

Reputation:

How to do Ctrl+Z with I/O redirection?

I wrote a complex program which works like a small shell and most of its hard work is done when the user presses ctrl+c or ctrl+z, how can I do such thing with file input redirection?

I thought writing ctrl+z will work but I was wrong. An example of test input file:

chprompt hello
sleep 2
sleep 3
sleep 5&

Side Question:

I noticed that in real shell when no command is running and I press Ctrl+z nothing happens but when I press Ctrl+c I see some text printed and a new line, why is this difference?

Upvotes: 0

Views: 389

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126243

Terminal control signals (ctrl-C and ctrl-Z) have nothing to do with I/O redirection. Redirecting I/O just affects where stdin reads from or where stdout writes to -- it does not affect the controlling terminal of any process.

When the user hits CtrlC or CtrlZ on a terminal, it sends a signal (SIGINT or SIGTSTP) to the controlling (foreground) process group of the terminal. It does not send any input to anyone reading the terminal, though if one of the processes in the foreground group is reading, it will get the signal (which will likely interrupt the reading). If a program reads a '\x03' or '\x1A' (the ascii/unicode character sometimes associated with ctrl-C or ctrl-Z) it just reads that character -- there's no interrupt or signal sent.

If you're trying to "simulate" a ctrl-C or Ctrl-Z for testing puposes, you (just) need to send a SIGINT or SIGTSTP to the process in question. There's no contents of a file you can use to cause it.

I noticed that in real shell when no command is running and I press Ctrl+z nothing happens but when I press Ctrl+c I see some text printed and a new line, why is this difference?

The shell has different signal handlers for SIGINT and SIGTSTP -- the one for SIGTSTP just completely ignores the signal, while the one for SIGINT prints an indication that it happened and another prompt.

Upvotes: 1

Related Questions