Get the App
SLTechnology News&Howtos  ›  Development  › 

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

Shulou Source: shulou.com Published: 2022-06-03 20:02:28 10月26日 Update

This article mainly introduces "how to force the PHP command line script single process to run". In the daily operation, I believe that many people have doubts about how to force the PHP command line script single process to run. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to force the PHP command line script single process to run". Next, please follow the editor to study!

The copy code is as follows:

/ * *

* guarantee single process

*

* @ param string $processName process name

* @ param string $pidFile process file path

* @ return boolean whether to continue with 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

}

}

/ * *

* obtain the Command corresponding to the current process

*

The * @ return string command and its arguments

, /

Function getCurrentCommand ()

{

$pid = posix_getpid ()

$command= exec ("/ bin/ps-p $pid-o command=")

Return $command

}

How to use it:

The copy 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")

}

At this point, the study on "how to force the PHP command line script single process to run" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Process command script force run code learning method more help practical next use method parameter file article theory knowledge article website Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Tech Info NVidia OPPO Reno Redmi