Why Background Processes Stop Spontaneously – Terminal Job Control

background-processiojob-controlterminal

Sometimes, some time after I've backgrounded a process with bg in bash, when I press Enter in the same shell to redisplay the prompt (just to check that I'm still in bash when some output from the background process has been displayed), the background process seems to stop spontaneously.

If I do bg again the same problem recurs.

The only way to fix it seems to be fg.

Why does this happen?

Best Answer

This usually happens if the process tries to read from its stdin stream. When the process is in the background, it receives a TTIN signal and is thus frozen (same behavior as a STOP signal). There is also the dual signal TTOU when a background process tries to write to its terminal.

Bringing it to the foreground resumes the process and allows it to read from your terminal.

Demo:

$ cat t.sh
#! /bin/sh
sleep 1
read dummy
$ ./t.sh &
[1] 3364
$ 
[1]+  Stopped                 ./t.sh
$ ps aux|grep t.sh
me  3364  0.0  0.0  11268  1200 pts/0    T    17:04   0:00 /bin/sh ./t.sh

One of the ways of avoiding this is to use nohup, but this can have strange effects if the program doesn't deal with having its input stream redirected to /dev/null.

Related Question