A method to force the PHP command line script to run _php instance

Source: Internet
Author: User

Copy Code code as follows:

/**
* Guaranteed Single Process
*
* @param string $processName process name
* @param string $pidFile process file path
* @return Boolean continues to execute the current process
*/
function singleprocess ($processName, $pidFile)
{
if (file_exists ($pidFile) && $fp = @fopen ($pidFile, "RB")
{
Flock ($FP, lock_sh);
$last _pid = fread ($fp, FileSize ($pidFile));
Fclose ($FP);

if (!empty ($last _pid))
{
$command = EXEC ("/bin/ps-p $last _pid-o command=");

if ($command = = $processName)
{
return false;
}
}
}

$cur _pid = Posix_getpid ();

if ($fp = @fopen ($pidFile, "WB")
{
Fputs ($fp, $cur _pid);
Ftruncate ($fp, strlen ($cur _pid));
Fclose ($FP);

return true;
}
Else
{
return false;
}
}

/**
* Gets the command corresponding to the current process
*
* @return string command and its arguments
*/
function Getcurrentcommand ()
{
$pid = Posix_getpid ();
$command = EXEC ("/bin/ps-p $pid-o command=");

return $command;
}

How to use:

Copy Code code as follows:

if (Singleprocess (Getcurrentcommand (), ' path/to/script.pid '))
{
Code goes here
}
Else
{
Exit ("Sorry, this script file has already been running ... \ n");
}

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.