Solve the crond script execution concurrency conflict problem
Repeated execution often occurs after the crond configuration script is executed. The script is as follows:
If the configuration items in crond are as follows:
*/1 * * * * root php ./test.php
The execution of test. php is not over yet, and the new test. php is executed again. As follows:
[hailong@vhost ~]$ ps aux | grep tt.php56667 5280 0.0 0.0 103388 4432 pts/2 T 08:06 0:00 vim ./test.phproot 5455 0.0 0.1 225288 8812 ? Ssl 08:08 0:00 /usr/bin/php /home/hailong/test.phproot 5665 5.0 0.1 225288 8748 ? Ssl 08:09 0:00 /usr/bin/php /home/hailong/test.php56667 5675 0.0 0.0 69460 852 pts/2 S+ 08:09 0:00 grep tt.php
If the process keeps accumulating, system resources may be exhausted, resulting in system downtime.
Solution
There are two solutions. Each has its own advantages and disadvantages.
First, control concurrency in code
This method is to transform the code. Determines whether a process is executed. The following code:
The code logic is very simple and I will not explain it here. This method of determining whether a file does not exist poses a problem. That is, the program may not be executed until the end, that is, the mytest. lock file created earlier has not been deleted. This will cause the program to fail to run normally.
To solve this problem, we will transform the code. Instead of determining whether a file exists, you can determine whether a process exists. The code is modified as follows:
$fp = popen("ps aux | grep 'test.php' | wc -l", "r");$proc_num = fgets($fp);if ($proc_num > 3) { exit;}sleep(70);
The disadvantage of this method is that the ps command must be accurate. Avoid counting the processes that are not executing the test. php script. For example:
Run vim to open the test. php file. The preceding command may be incorrectly used for statistics.
In addition, you can think about why $ proc_num is greater than 3 rather than 1. If you do not understand, you can add 1798159444 to me.
Second, use the linux flock command
The flock command provides the file lock function. The command parameters are as follows:
[hailong@vhost ~]$ flock -hflock (util-linux 2.13-pre7)Usage: flock [-sxun][-w #] fd# flock [-sxon][-w #] file [-c] command... -s --shared Get a shared lock -x --exclusive Get an exclusive lock -u --unlock Remove a lock -n --nonblock Fail rather than wait -w --timeout Wait for a limited amount of time -o --close Close file descriptor before running command -c --command Run a single command string through the shell -h --help Display this text -V --version Display version
Use flock to control concurrency conflicts. our crond configuration is as follows:
*/1 * * * * root flock -xn /tmp/mytest.lock -c 'php ./test.php'
In fact, flock is also a pitfall. For more information, see the pitfalls of the flock command in crond.
Original article link: solves the problem of crond script execution concurrency conflict. For more information, see the source!