search
HomeBackend DevelopmentPHP TutorialDetailed explanation of common implementation methods of daemon process in PHP

This article mainly introduces two common implementation methods of PHP daemon process, and analyzes the principles, related implementation methods and operating precautions of PHP daemon process with specific examples. Friends in need can refer to the following

The examples in this article describe two common implementation methods of PHP daemons. Share it with everyone for your reference, the details are as follows:

The first way is to use nohup and & together.

Adding the ampersand after the command allows the started process to run in the background without occupying the console. The console can also run other commands. Here I use a while Infinite loop for demonstration, the code is as follows


<?php
while(true){
    echo time().PHP_EOL;
    sleep(3);
}

Use & method to start the process


[root@localhost php]# php deadloop.php &
[1] 3454
[root@localhost php]# ps aux | grep 3454
root   3454 0.0 0.8 284544 8452 pts/0  T  18:06  0:00 php deadloop.php
root   3456 0.0 0.0 103316  896 pts/0  S+  18:08  0:00 grep 3454
[1]+ Stopped         php deadloop.php
[root@localhost php]#

You can see The process does not occupy the console, and the console can also run other commands. At this time, we can also use the fg command to restore the process to the mode of normally occupying the console.


[root@localhost php]# fg
php deadloop.php
1470996682
1470996685
1470996688
1470996691

The above is a brief introduction to the & command

Let’s look at another command nohup

Add nohup before the command to start The process will ignore the Linux hang-up signal (SIGHUP), so under what circumstances will the SIGHUP signal under Linux be triggered? The following content is taken from Baidu Encyclopedia:

SIGHUP will be triggered in the following three situations Sent to the corresponding process:

1. When the terminal is closed, the signal is sent to the session first process and the process submitted as a job (that is, the process submitted with the & symbol)
2. session When the first process exits, this signal is sent to every process in the foreground process group in the session
3. If the parent process exits, the process group becomes an orphan process group, and there are processes in the process group that are stopped ( When a SIGSTOP or SIGTSTP signal is received), the signal will be sent to every process in the process group.

Combining 1 and 2, we know that no matter whether the process is started in & (job mode) or not, the SIGHUP signal will be received when closing the terminal. So how will the process handle the SIGHUP signal? See also excerpted from Baidu A sentence from Encyclopedia

The system's default processing of the SIGHUP signal is to terminate the process that receives the signal. Therefore, if the signal is not captured in the program, the process will exit when the signal is received.

That is to say, closing the terminal process will receive the SIGHUP signal, and the default processing method of this signal is to end the process. Of course, we can also handle the signal ourselves, or ignore it, which is also an example of the above loop. , let’s make a slight improvement


<?php
declare(ticks = 1);
pcntl_signal(SIGHUP, function(){
    // 这地方处理信号的方式我们只是简单的写入一句日志到文件中
    file_put_contents(&#39;logs.txt&#39;, &#39;pid : &#39; . posix_getpid() . &#39; receive SIGHUP 信号&#39; . PHP_EOL);
});
while(true){
    echo time().PHP_EOL;
    sleep(3);
}

We don’t have to be so troublesome, we just need to use the nohup command provided by linux, but when we use nohup to start the process, close the terminal, The process will ignore the SIGHUP signal and will not exit. First, remove the signal processing code just now. Then run nohup.


[root@localhost php]# nohup php deadloop.php

nohup: Ignore input and append output to "nohup.out"

And nohup will redirect the program's output to the current directory by default nohup.out file, if there is no writable permission, write $homepath/nohup.out


[root@localhost php]# ls
cmd.sh deadloop.php getPhoto.php nohup.out pics
[root@localhost php]# tail -f nohup.out
1470999772
1470999775
1470999778
1470999781
1470999784
1470999787
1470999790
1470999793
1470999796
1470999799
1470999802

At this time, close the terminal, the process will not end, but will change It became an orphan process (ppid=1) because the parent process that created it exited.


[root@localhost ~]# ps -ef | grep 3554
root   3554 3497 0 19:09 pts/0  00:00:00 php deadloop.php
root   3575 3557 0 19:10 pts/1  00:00:00 grep 3554
[root@localhost ~]# ps -ef | grep 3554
root   3554   1 0 19:09 ?    00:00:00 php deadloop.php
root   3577 3557 0 19:10 pts/1  00:00:00 grep 3554
[root@localhost ~]#

Conclusion: So when we combine the nohup and & methods, the started process will not occupy the console nor rely on the console , after the console is closed, the process is adopted by process No. 1 and becomes an orphan process. This is very similar to the mechanism of a daemon process.


[root@localhost php]# nohup php deadloop.php >logs.txt 2>error.txt &
[1] 3612
[root@localhost php]# ps -ef |grep 3612
root   3612 3557 0 19:18 pts/1  00:00:00 php deadloop.php
root   3617 3557 0 19:19 pts/1  00:00:00 grep 3612
[root@localhost php]#

Among them >logs.txt redirects standard output, 2>error.txt redirects standard error output.

The above is an introduction to the first implementation method.

The second implementation method is to implement it through code according to the rules and characteristics of the daemon process,The biggest feature of the daemon process is that it is separated from the user terminal and Session , the following is the implemented code, and the key places are commented.


<?php
$pid = pcntl_fork();
if ($pid == -1)
{
  throw new Exception(&#39;fork子进程失败&#39;);
}
elseif ($pid > 0)
{
  //父进程退出,子进程变成孤儿进程被1号进程收养,进程脱离终端
  exit(0);
}
// 最重要的一步,让该进程脱离之前的会话,终端,进程组的控制
posix_setsid();
// 修改当前进程的工作目录,由于子进程会继承父进程的工作目录,修改工作目录以释放对父进程工作目录的占用。
chdir(&#39;/&#39;);
/*
 * 通过上一步,我们创建了一个新的会话组长,进程组长,且脱离了终端,但是会话组长可以申请重新打开一个终端,为了避免
 * 这种情况,我们再次创建一个子进程,并退出当前进程,这样运行的进程就不再是会话组长。
 */
$pid = pcntl_fork();
if ($pid == -1)
{
  throw new Exception(&#39;fork子进程失败&#39;);
}
elseif ($pid > 0)
{
  // 再一次退出父进程,子进程成为最终的守护进程
  exit(0);
}
// 由于守护进程用不到标准输入输出,关闭标准输入,输出,错误输出描述符
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
/*
 * 处理业务代码
 */
while(TRUE)
{
  file_put_contents(&#39;log.txt&#39;, time().PHP_EOL, FILE_APPEND);
  sleep(5);
}

The above is the detailed content of Detailed explanation of common implementation methods of daemon process in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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 Mac version

Dreamweaver Mac version

Visual web development tools