I have put together a small bash script that launches then periodically checks if my main program is running (console application, no gui). My main application is supposed to be the guts of an appliance (embedded) system and it needs to run continuously.
# Start myProgram
/path/to/myProgram &
while true
do
if [ -n "`ps ax | grep -v grep | grep myProgram`" ]
then
sleep 5 2>&1 > /dev/null
else
/path/to/myProgram &
fi
done
My main program contains a c++ select() (with timer) loop that watches several TCP, UDP and Unix Domain sockets as well as stdin.
When run in the foreground, myProgram run as expected. When no one sends it data it just sits in the select() times out every 2 seconds, fiddles with timers and such, then waits again. Any keyboard activity ending with an ENTER is grabbed and processed. Console input puts up a “N bytes received at console” message (for now!)
When my script launches myProgram in the background, however, I get a constant stream of “) bytes received at console” messages as if stdin were closing and reopening or some other app is sending a stream of ENTERs to my app.
Could someone explain please?
If, in fact, the state of being in the background is causing stdin to close/reopen ovr and over, is it possible for myProgram to detect that it is backgrounded and disconnect from stdin? Will I need to disconnect from stdout and stderr as well? Guess that’d make me a daemon.
And, lastly, would the watchdog program be a better way to track that myProgram is still running? Can watchdog restart the program rather than restarting the whole machine?
Only foreground jobs can have standard input attached to the terminal. Background jobs are suspended if they attempt to read from the terminal. You’ll have to leave the job in the foreground, or redirect standard input from somewhere else.