How to force a PHP command line script to run a single process

Source: Internet
Author: User
This article describes a function that forces PHP to execute in a single process. it is mostly used in php command lines and some special requirements. For more information, see The code is as follows:
/**
* Single process guarantee
*
* @ Param string $ processName process name
* @ Param string $ pidFile process file path
* @ Return boolean whether to continue executing 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;
}
}

/**
* Get the Command corresponding to the current process
*
* @ Return string command and its parameters
*/
Function getCurrentCommand ()
{
$ Pid = posix_getpid ();
$ Command = exec ("/bin/ps-p $ pid-o command = ");

Return $ command;
}

Usage:
The code is 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.