skip to Main Content

i’m creating a socket server with ReactPHP and i need it to run forever.
I also have a command panel where i have to check if the process is running, and i can stop or start it (or restart it).

I don’t know howe to achieve this.

My plan was:

  • With play button: start the php command shell_exec with simply "php script.php".
  • With stop button i can do in 2 ways: 1. i can set in the loop a timer that every 5 seconds checks if there is file inside the folder (like "stop.lock") and then stop the process. 2. i can save the process PID in the database, and so clicking the stop button i can just kill the process.
  • Checking online status: I can make another script that tries to connect to the IP/port and if succeeds is online, if not (timeout 5 seconds) is offline.

I also want the script stay always in the listening status, so how can i make the script auto-start if for example i have to restart my server?
I was thinking about a cron trying to connect to the server every minutes; and if it fails, it will just lauch again shell_exec(‘php script.php’);

How is the best solution to handle all? (Server OS is CentOS 7)

2

Answers


  1. As @Volker said, just stop the loop if you want to stop it gracefully. You could check periodically a file or query a table but that’s not a great way.

    A nice flow could be to listen to an admin message to stop the server. Of course, you should care of authenticating who can stop the server. This way it will stop without having to wait an interval to run, and you reduce the overhead of querying periodically your filesystem or your database.

    Another cool way could be using RabbitMQ or a similar queue service. You just listen to your queue server, and you can send a message from your script to RabbitMQ, and from there to your server.

    Good luck!

    Edit: If you are running your server with systemd, a great way of handling it could be just to listen to a system signal to gracefully stop the application. Take a look at addSignal, you can handle a kill by pid, but also through systemd.

    Login or Signup to reply.
  2. To handle graceful shutdown versus long running streamed response I’ve created a acquire/release like mechanism.

    When a handler starts streaming a long response it acquires a lock and when streaming is done it releases it (it’s just an array of uniqid()).

    The server can decide to wait if there is active locks.

    I use supervisor to handle the start/stop with a SIGTERM signal.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search