If a Bash script contains `read -p "Press [Enter] key to continue..."` and the script is started in the background, what happens to the `read` command? Does the script hang, immediately receive EOF, or get suspended while waiting for terminal input?
3 Answers
So it is not always correct to say that the command simply hangs. With standard input detached, `read` gets EOF immediately; with a terminal still attached, the background job is suspended until it is brought to the foreground. If background input is required, provide it explicitly through a file, pipe, or named pipe instead of expecting interactive terminal input.
It depends on how the script is started. When a non-interactive parent script launches `./script &`, Bash commonly connects the background job's standard input to `/dev/null`. In that case, `read` immediately encounters EOF, returns a failure status, and the script continues without waiting for input—effectively similar to pressing Ctrl+D.
When you launch `./script &` directly from an interactive shell with job control enabled, the background process may still have the terminal as its input. A terminal normally prevents background processes from reading, so the kernel sends the process `SIGTTIN`, suspending it. Resuming it with `bg` causes it to be suspended again when it tries to read; bringing it to the foreground with `fg` lets it read normally.

The signal involved here is `SIGTTIN`, not `SIGTSTP`. `SIGTTIN` is specifically used when a background process attempts to read from its controlling terminal. A related setting is `stty tostop`, which can suspend background jobs that attempt terminal output via `SIGTTOU`.