Table of Contents
Reply content:
Home Backend Development PHP Tutorial node.js - How can I keep my php script running as a daemon?

node.js - How can I keep my php script running as a daemon?

Aug 23, 2016 am 09:17 AM
centos linux node.js php ubuntu

I wrote a server using swoole. I plan to hang it on the server as a daemon and run it continuously. This will also allow the script to restart as soon as possible after unexpectedly exiting due to an error. How can I do this?

Reply content:

I wrote a server using swoole. I plan to hang it on the server as a daemon and run it continuously. This will also allow the script to restart as soon as possible after unexpectedly exiting due to an error. How can I do this?

The linux nohup command runs this php script and then writes a shell to monitor the running status of this script. If the script dies, restart it

Just write the script as a loop, such as while(1), so that it can run forever.

In this script header, this judgment, if there is already a process of this script, exit directly, and execute if there is no process,

Write another linix scheduled task, such as executing this php script every minute.

After executing the script once, the script will keep running. The scheduled task will execute the script every minute. If the script is alive, it will exit directly. If it dies, it will start execution.

Write the php script. It is recommended to check the memory usage regularly and not write the core logic. This is related to business.

<code>if(memory_get_usage()>100*1024*1024){
    exit(0);//大于100M内存退出程序,防止内存泄漏被系统杀死导致任务终端
}</code>
Copy after login

Assume the path of the php file is /root/run.php
Open the terminal

<code>setsid php /root/run.php > /dev/null &</code>
Copy after login

Edit the process monitoring script to automatically restart the process when it does not exist /root/monitor.sh

<code>#!/bin/bash
alive=`ps aux|grep root\/run|grep -v grep|wc -l`
if [ $alive -eq 0]
then
php /root/run.php > /dev/null &
fi</code>
Copy after login

Add scheduled tasks (detected every minute)

<code>crontab -e
* * * * * /root/monitor.sh > /dev/null &</code>
Copy after login

Handmade

Use a simple and reliable Shell script to protect a PHP service that may exit suddenly

Add the boot command to /etc/rc.local:

<code>nohup /path/to/swoole.sh >>/path/to/swoole.sh.log 2>&1 &</code>
Copy after login

swoole.sh content is as follows:

<code>#!/bin/sh
PREFIX=/home/eechen
INTERVAL=1
nohup php ${PREFIX}/swoole.php >>${PREFIX}/swoole.log 2>&1 & echo $! > ${PREFIX}/swoole.pid
while [ 1 ]; do
    if [ ! -d /proc/`cat ${PREFIX}/swoole.pid` ]; then
        nohup php ${PREFIX}/swoole.php >>${PREFIX}/swoole.log 2>&1 & echo $! > ${PREFIX}/swoole.pid
        echo 'NEW_PID:'`cat ${PREFIX}/swoole.pid && date '+%Y-%m-%d %H:%M:%S'`
    fi
    sleep ${INTERVAL}
done</code>
Copy after login

Among them:

<code>nohup 表示忽略SIGHUP信号(编号1),比如退出终端时发送的SIGHUP信号(kill -SIGHUP PID)会被忽略掉.
>>${PREFIX}/swoole.log 表示把标准输出重定向(>>表示追加,>表示覆盖)到文件swoole.log
2>&1 表示将标准错误(2:stderr)重定向到标准输出(1:stdout).
结尾加上&表示将命令放入后台运行.
$! 表示前面运行在后台的PHP进程PID.</code>
Copy after login

That is, swoole.sh checks whether the directory /proc/PID exists every 1 second. If it does not exist, the service is restarted.
swoole.sh.log records the time when the service restarts.
swoole.log records It is the output of the service itself.

For example, use Shell to protect vmstat:

<code>vmstat.sh
#!/bin/sh
PREFIX=/home/eechen
INTERVAL=1
nohup vmstat 1 >>${PREFIX}/vmstat.log 2>&1 & echo $! > ${PREFIX}/vmstat.pid
while [ 1 ]; do
    if [ ! -d /proc/`cat ${PREFIX}/vmstat.pid` ]; then
        nohup vmstat 1 >>${PREFIX}/vmstat.log 2>&1 & echo $! > ${PREFIX}/vmstat.pid
        echo 'NEW_PID:'`cat ${PREFIX}/vmstat.pid && date '+%Y-%m-%d %H:%M:%S'`
    fi
    sleep ${INTERVAL}
done

#运行
nohup /home/eechen/vmstat.sh >>/home/eechen/vmstat.sh.log 2>&1 &
#杀死,可以看到vmstat被重启
kill `cat /home/eechen/vmstat.pid`</code>
Copy after login

This vmstat.sh script can also be implemented in PHP:

<code>nohup php /home/eechen/vmstat.php >>/home/eechen/vmstat.php.log 2>&1 &
<?php
$prefix = '/home/eechen';
$interval = 1;
shell_exec("nohup vmstat 1 >>$prefix/vmstat.log 2>&1 & echo $! > $prefix/vmstat.pid");
while ( 1 ) {
    if ( !file_exists('/proc/'.trim(file_get_contents("$prefix/vmstat.pid"))) ) {
        shell_exec("nohup vmstat 1 >>$prefix/vmstat.log 2>&1 & echo $! > $prefix/vmstat.pid");
        echo 'NEW_PID:'.trim(file_get_contents("$prefix/vmstat.pid")).' '.date('Y-m-d H:i:s');
    }
    sleep($interval);
}</code>
Copy after login

1.crontab must be there, check if it exists every minute, (ps -ef | grep..), if it exits, if not, create and execute it
2. A process that has been running can loop endlessly...
3.crontab The script can detect the status of your always-running process. If there is a problem, it has been waiting, no response or other problems, you have to kill and restart it yourself

Linux shell execution

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 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.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

See all articles