What's the best way to keep a PHP script running as a daemon?

后端 未结 9 1123
小蘑菇
小蘑菇 2020-12-24 03:37

What is the best way to keep a PHP script running as a daemon, and what\'s the best way to check if needs restarting.

I have some scripts that need to run 24/7 and f

相关标签:
9条回答
  • 2020-12-24 04:32

    I've had success with running a wget and sending the result to /dev/null on a shared server.

    0 讨论(0)
  • 2020-12-24 04:37

    Daemon is a linux process that runs in background; apache or mysql are daemons. In a linux environment, we can run a background program using cronjob, but it has some limitations, and in some scenarios it' s not a good idea. For example, using cronjob, we can't control if the previously run has finished yet. So often it's more convenient run a process as a daemon.

    // Daemonize
    $pid = pcntl_fork(); // parent gets the child PID and child gets 0
    if($pid){ // if pid is not 0
         // Only the parent will know the PID. Kids aren't self-aware
         // Parent says goodbye!
         print "Parent : " . getmypid() . " exiting\n";
         exit();
    }
    print "Child : " . getmypid() . "\n";
    

    The code above is taken from very good article about how to create a daemon in php. You can read this at link

    0 讨论(0)
  • 2020-12-24 04:39

    I agree that PHP is not the best tool for this, however I can understand why you want to use PHP so you can reuse components from your application such as database access, and so on.

    I had a similar problem and I ended up developing The Fat Controller which is a daemon written in C that can run PHP scripts. It can also run as a multithreaded daemon, running many instances of a script in parallel.

    There's more information and use cases here: http://www.4pmp.com/fatcontroller/

    0 讨论(0)
提交回复
热议问题