How to force a PHP command line script to run a single process _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Method to Force a single process to run the PHP command line script. Copy the code as follows: *** ensure that a single process ** @ paramstring $ processName process name * @ paramstring $ pidFile process file path * @ returnboolean whether to continue executing the current process 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 ");
}

The http://www.bkjia.com/PHPjc/754797.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/754797.htmlTechArticle code is as follows: /*** ensure that a single process ** @ param string $ processName process name * @ param string $ pidFile process file path * @ return boolean whether to continue executing the current process...

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.