screen: Force program to continue after logging-off from the console

So, there I was… needing to have any solution, that will allows me to write my very own port listener. Since the only language, in which I am handy is PHP, I was forced to be able to run PHP script without interruption, 24 hours a day, 7 days a week. That was a bit of challenge for me, given my quite very limited Linux knowledge, but — as they say — the only thing not possible in IT is to open an umbrella in your ass! :>

Running script forever

If you want to run a PHP script endlessly, try to run it as daemon (with & at the end). For example:

/mnt/ext/opt/apache/bin/php -f /share/Web/puk/gateway.php&

You’ll get a PID of created process in response. You can use that PID as kill command parameter to end it.

For some reason (probably due to stupidity of QNAP support and removing too much from core Linux), you must keep your console connection open and active. Once you log-off or are logged-off, script dies (though it was a daemon). Using screen command, as described below, seems to be the only way.

There is no screen command in default installation of QNAP TS-210! You have to manually install it.

Fortunately, if you have Optware installed (read this, if you don’t), all you have to do is to execute ipkg install screen command.

Using screen command

To run a “virtual” terminal call:

screen -S [nameScreen]

Any commands executed in it will be executed in some kind of sandbox, but they’ll be of course executed within the system.

Regular exit from virtual terminal is by executing exit command inside it.

If, instead of above Ctrl+A followed by Ctrl+D is pressed, then current instance is exited, but it still runs in background. Thus, allowing to log-off console and leave script, program or service running indefinitely (until instance is killed or machine turned off).

You can browse all active screen instances anytime, by executing:

screen -ls

To reopen existing instance run:

screen -r [nameScreen]

It is even possible to execute particular command or script inside active screen instance without visiting it. To achieve this one must execute:

screen -dmS [nameScreen] [operationToDo]

As a base behavior, when command or script executed “remotely” in some screen instance ends work, that instance is killed automatically. This feature is most wanted in most cases. In certain rare occasions this may be avoided by executing:

screen -dmS name sh -c '/path/to/a/; exec bash'

This article is based on my own knowledge and experience, on my on-the-fly translation of this Polish article and on this Unix & Linux SE answer.

Leave a Reply