Introduction to how PHP creates a single-instance background process method

Source: Internet
Author: User
This article mainly introduces the method of PHP to create a single background process, involving PHP for process start, create, judge, stop and other related operations skills, the need for friends can refer to the next

The example in this article describes how PHP creates a singleton background process. Share to everyone for your reference, as follows:

You can start a PHP background process by using the following statement:


$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 be run as a daemon.

If you want this background process to run as a singleton, you can record/determine if the process is running by using the following method


Query the database for process id$query = "Select pid from ' daemons ' WHERE ' pid ' = ' LIMIT 1 '; $result = mysql_query ($query); $pid = mysql_result ($result, 0, ' pid '),//check if the process is runningexec ("PS $pid", $pState); if ((Count ($pSta TE) >= 2) &&!empty ($pid)) {echo "RUNNING";} Else{echo "INACTIVE";}

You can also write the PID to a file, but in a distributed task environment, it is better to put it in the database.

To 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 and 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.