Example of how to create a single backend process in PHP and a background process

Source: Internet
Author: User

Example of how to create a single backend process in PHP and a background process

This example describes how to create a single-instance background process in PHP. We will share this with you for your reference. The details are as follows:

You can use the following statement to start a PHP background process:

$ Command = "php script. php"; $ pid = exec ("nohup $ command>/dev/null 2> & 1 & echo $! ");

Nohup indicates that the process is independent of the created user and can run in daemon mode.

If you need to run the background process as a Singleton, you can use the following method to record/determine whether the process is running

// Query the database for process id $ query = "SELECT pid FROM 'daemons' WHERE 'pid '= '000000' LIMIT 1"; $ result = mysql_query ($ query ); $ pid = mysql_result ($ result, 0, 'pid '); // check if the process is runningexec ("ps $ pid", $ pState ); if (count ($ pState)> = 2 )&&! Empty ($ pid) {echo "RUNNING";} else {echo "INACTIVE ";}

You can also write the pid to a file, but it is better to store it in a database if it is in a distributed task environment.

Stop a background process:

// Check if the process from the database is runningexec ("ps $ pid", $ pState); if (count ($ pState)> = 2 )) {// if the process is running, kill itexec ("kill $ pid"); // update database row with an empty process id}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.