Table of Contents
PHP implements program singleton operation
Home Backend Development PHP Tutorial PHP implementation of program singleton operation_PHP tutorial

PHP implementation of program singleton operation_PHP tutorial

Jul 13, 2016 am 10:19 AM
program

PHP implements program singleton operation

1. Scene description:

Recently, in our business, we need to constantly monitor changes in a directory. If there are files in the directory, start a PHP script to process them. The initial solution is to use crontab to execute the sh script. The script is roughly as follows:

SOK=`ps -ef |grep /www/sender.sh | grep -v grep|wc -l`
if [[ $SOK < 2 ]];then
        for f in `ls /www/queue`; do
                        php /www/logsender.php /www/queue/$f
        done
Copy after login


An exception occurred during actual operation: the method of ps -ef | grep xxx may not be able to correctly determine whether the process is executing, and the if condition will never be established, causing the PHP script to never be executed. After consideration, we decided to create a class that is independent of other modules and can implement singleton operation of the process to solve this problem.

2. Scheme design

1. Implement process singleton through PID file

2. Automatically create and delete PID files when the program starts and exits, so that no business code is required to consider PID file deletion

3. Try to ensure code independence without affecting business code

3. Principle

1. Start creating PID file

2. Bind semaphores such as program exit and kill, used to delete PID files

3. Add a destructor and delete the PID file when the object is destroyed

4. Problems encountered

When the program exits normally, the semaphore cannot be captured. I don’t know if the semaphore is selected wrongly. Signals such as ctrl+c are normal. If the semaphore can be captured when the program exits normally, it can be replaced by destruction. Function solution, more stable

5. Code

<!--?php
/**
 * Created by PhpStorm.
 * User: huyanping
 * Date: 14-8-13
 * Time: 下午2:25
 *
 * 实现程序单例运行,调用方式:
 * declare(ticks = 1);//注意:一定要在外部调用文件中首部调用该声明,否则程序会无法监听到信号量
 * $single = new DaemonSingle(__FILE__);
 * $single--->single();
 *
 */
 
class DaemonSingle {
 
    //PID文件路径
    private $pid_dir;
 
    //PID文件名称
    private $filename;
 
    //PID文件完整路径名称
    private $pid_file;
 
    /**
     * 构造函数
     * @param $filename
     * @param string $pid_dir
     */
    public function __construct($filename, $pid_dir=&#39;/tmp/&#39;){
        if(empty($filename)) throw new JetException(&#39;filename cannot be empty...&#39;);
        $this->filename = $filename;
        $this->pid_dir = $pid_dir;
        $this->pid_file = $this->pid_dir . DIRECTORY_SEPARATOR . substr(basename($this->filename), 0, -4) . &#39;.pid&#39;;
    }
 
    /**
     * 单例模式启动接口
     * @throws JetException
     */
    public function single(){
        $this->check_pcntl();
        if(file_exists($this->pid_file)) {
            throw new Exception(&#39;the process is already running...&#39;);
        }
        $this->create_pid_file();
    }
 
    /**
     * @throws JetException
     */
    private function create_pid_file()
    {
        if (!is_dir($this->pid_dir)) {
            mkdir($this->pid_dir);
        }
        $fp = fopen($this->pid_file, &#39;w&#39;);
        if(!$fp){
            throw new Exception(&#39;cannot create pid file...&#39;);
        }
        fwrite($fp, posix_getpid());
        fclose($fp);
        $this->pid_create = true;
    }
 
    /**
     * 环境检查
     * @throws Exception
     */
    public function check_pcntl()
    {
        // Make sure PHP has support for pcntl
        if (!function_exists(&#39;pcntl_signal&#39;)) {
            $message = &#39;PHP does not appear to be compiled with the PCNTL extension.  This is neccesary for daemonization&#39;;
            throw new Exception($message);
        }
        //信号处理
        pcntl_signal(SIGTERM, array(&$this, signal_handler));
        pcntl_signal(SIGINT, array(&$this, signal_handler));
        pcntl_signal(SIGQUIT, array(&$this, signal_handler));
 
        // Enable PHP 5.3 garbage collection
        if (function_exists(&#39;gc_enable&#39;)) {
            gc_enable();
            $this->gc_enabled = gc_enabled();
        }
    }
 
    /**
     * 信号处理函数,程序异常退出时,安全删除PID文件
     * @param $signal
     */
    public function signal_handler($signal)
    {
        switch ($signal) {
            case SIGINT :
            case SIGQUIT:
            case SIGTERM:{
                self::safe_quit();
                break;
            }
        }
    }
 
    /**
     * 安全退出,删除PID文件
     */
    public function safe_quit()
    {
        if (file_exists($this->pid_file)) {
            $pid = intval(posix_getpid());
            $file_pid = intval(file_get_contents($this->pid_file));
            if($pid == $file_pid){
                unlink($this->pid_file);
            }
        }
        posix_kill(0, SIGKILL);
        exit(0);
    }
 
    /**
     * 析构函数,删除PID文件
     */
    public function __destruct(){
            $this->safe_quit();
    }
}
Copy after login



www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/871198.htmlTechArticlePHP implementation program singleton operation 1. Scenario description: Recently, our business needs to constantly monitor changes in a directory , if there are files in the directory, start the PHP script to process them. Most...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to make Google Maps the default map in iPhone How to make Google Maps the default map in iPhone Apr 17, 2024 pm 07:34 PM

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

Fix: Operator denied request error in Windows Task Scheduler Fix: Operator denied request error in Windows Task Scheduler Aug 01, 2023 pm 08:43 PM

To automate tasks and manage multiple systems, mission planning software is a valuable tool in your arsenal, especially as a system administrator. Windows Task Scheduler does the job perfectly, but lately many people have reported operator rejected request errors. This problem exists in all iterations of the operating system, and even though it has been widely reported and covered, there is no effective solution. Keep reading to find out what might actually work for other people! What is the request in Task Scheduler 0x800710e0 that was denied by the operator or administrator? Task Scheduler allows automating various tasks and applications without user input. You can use it to schedule and organize specific applications, configure automatic notifications, help deliver messages, and more. it

How to sort photos by face on Windows 10 and 11 How to sort photos by face on Windows 10 and 11 Aug 08, 2023 pm 10:41 PM

The operation of Windows is getting better and better with every version, with attractive features to improve the user experience. One feature users will want to explore on Windows 10 and 11 is the ability to sort photos by faces. This feature allows you to group photos of friends and family using facial recognition. Sounds fun, right? Read on to learn how to take advantage of this feature. Can I group photos by faces on Windows? Yes, you can use the Photos app to group pictures by faces on Windows 10 and 11. However, this feature is not available on the Photos app version. Additionally, you can link these photos to contacts using the People tab. Therefore, using this function you can

How to write a simple countdown program in C++? How to write a simple countdown program in C++? Nov 03, 2023 pm 01:39 PM

C++ is a widely used programming language that is very convenient and practical in writing countdown programs. Countdown program is a common application that can provide us with very precise time calculation and countdown functions. This article will introduce how to use C++ to write a simple countdown program. The key to implementing a countdown program is to use a timer to calculate the passage of time. In C++, we can use the functions in the time.h header file to implement the timer function. The following is the code for a simple countdown program

How to Automatically Toggle iPhone Orientation Lock for Specific Apps How to Automatically Toggle iPhone Orientation Lock for Specific Apps Jun 06, 2023 am 08:22 AM

In iOS, many apps display different views when you rotate your iPhone from portrait to landscape. Depending on the app and how it's used, this behavior isn't always desirable, which is why Apple includes an orientation lock option in Control Center. However, some apps work more usefully with orientation lock disabled—think YouTube or the Photos app, where rotating the device to landscape provides a better full-screen viewing experience. If you prefer to stay locked down, you'll have to disable it in Control Center to get a full-screen experience every time you open these types of apps. Then when you close the app, you have to remember to turn orientation lock back on, which isn't ideal. Fortunately, you can create

Clock app missing in iPhone: How to fix it Clock app missing in iPhone: How to fix it May 03, 2024 pm 09:19 PM

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

How to open a website using Task Scheduler How to open a website using Task Scheduler Oct 02, 2023 pm 11:13 PM

Do you frequently visit the same website at about the same time every day? This can lead to spending a lot of time with multiple browser tabs open and cluttering the browser while performing daily tasks. Well, how about opening it without having to launch the browser manually? It's very simple and doesn't require you to download any third-party apps, as shown below. How do I set up Task Scheduler to open a website? Press the key, type Task Scheduler in the search box, and then click Open. Windows On the right sidebar, click on the Create Basic Task option. In the Name field, enter the name of the website you want to open and click Next. Next, under Triggers, click Time Frequency and click Next. Select how long you want the event to repeat and click Next. Select enable

Can't allow access to camera and microphone in iPhone Can't allow access to camera and microphone in iPhone Apr 23, 2024 am 11:13 AM

Are you getting "Unable to allow access to camera and microphone" when trying to use the app? Typically, you grant camera and microphone permissions to specific people on a need-to-provide basis. However, if you deny permission, the camera and microphone will not work and will display this error message instead. Solving this problem is very basic and you can do it in a minute or two. Fix 1 – Provide Camera, Microphone Permissions You can provide the necessary camera and microphone permissions directly in settings. Step 1 – Go to the Settings tab. Step 2 – Open the Privacy & Security panel. Step 3 – Turn on the “Camera” permission there. Step 4 – Inside, you will find a list of apps that have requested permission for your phone’s camera. Step 5 – Open the “Camera” of the specified app

See all articles