Friday, October 29, 2021

[SOLVED] nohup process stops running a few minutes after terminal closed

Issue

I want a program (written in php) to run on a remote server even if after I logout. The program is very simple: it does nothing but sleep for 10s (just for a test), like the following:

function index() 
{
    while(true)
    {
        sleep(10);
    }
}

So I connect to the remote server via SSH. And then launch the program like this:

  nohup php -f index.php &

I want it to run in the background on the server after I log out. But I find that everytime after I close the terminal the program can only run for around 10 minutes and then stop, though it does not stop immediately after terminal closed. If I do not close the terminal, it can keep running forever (as expected). Could anyone tell me what is the reason? And how to solve the problem? I have also tried using "disown" as is suggested in this post but got the same problem: How to make a programme continue to run after log out from ssh? By the way, I am using shared remote host, so it could be due to some server settings but it's strange because it works fine with terminal open.


Solution

You can try using disown right after your nohup command.

If it still doesn't work, consider using screen instead. It is a useful utility allowing "virtual terminals" to run, even after logout.

  1. Create a screen using screen -dmS someName. (e.g. screen -dmS myPhpScript)
  2. Enter your screen using screen -r, your window will be cleared.
  3. Execute your command (php -f index.php, no &!)
  4. Exit the screen, by doing [Ctrl]+[A] (which seems to do nothing), and then pressing [D]. The screen will stay in background. You'll come back to the previous prompt (just before step 2), with a message indicating [detached from XXXXX.someName].
  5. You can get back to the screen using screen -r or screen -x someName.


Answered By - HeySora