


How to get PHP script to run in the background and terminate the process via Enter?
Apr 01, 2025 am 07:48 AMTips for getting PHP scripts to run in the background and terminate gracefully
This article discusses how to make PHP scripts run in the background and provides a more convenient termination method than ctrl c
, that is, end the process by pressing Enter. It should be noted that PHP itself is not a daemon manager, which is different from tools such as Workerman. Tools such as Workerman usually have built-in background operation and process management mechanisms. For ordinary PHP scripts, we need to use system commands and some skills.
First, suppose we have a PHP script called s.php
, with its core loop as follows:
<?php cli_set_process_title('queue-server'); while (true) { // ...Your business logic... }
Running php s.php
directly will cause the script to run in the terminal foreground. To make it run in the background and be able to terminate with the Enter key, we can use the following method:
Method 1: Combining nohup
and screen
or tmux
The nohup
command can ignore the hangup signal and make the script continue to run in the background. But it lacks a convenient termination mechanism. screen
or tmux
is a terminal multiplexer that allows you to work in multiple terminal sessions and can easily manage background processes.
-
Start the script using
screen
ortmux
:screen -dmS queue-server nohup php s.php 2>&1 &
This line of command will start a
screen
session calledqueue-server
in the background and runnohup php s.php 2>&1 &
in it.-dmS
parameters represent separation mode, display name and create session respectively.2>&1
redirects the standard error to the standard output. -
Terminate script:
a. Use
screen -r queue-server
to reconnect to thequeue-server
session. b. PressCtrl a
in the session and then pressk
(orCtrl c
) to terminate the process.The usage method of
tmux
is similar, except that the commands are slightly different, please refer to the documentation oftmux
.
Method 2: Use PHP's pcntl
extension (more advanced, you need to understand process management)
PHP's pcntl
extension provides process control functions, allowing more granular process management to be implemented inside PHP scripts. This requires more in-depth programming knowledge, but allows for more flexible control. Here is a simple example that listens for standard input and terminates the process when the Enter key is received:
<?php cli_set_process_title('queue-server'); $stdin = fopen('php://stdin', 'r'); declare(ticks=1); register_tick_function(function() use ($stdin){ $line = fgets($stdin); if ($line !== false && trim($line) === "") { exit(0); } }); while (true) { // ...Your business logic... usleep(100000); // Avoid excessive CPU usage}
This script listens to standard input and ends the process when a blank line (Enter key) is detected. It should be noted that pcntl
extension needs to be enabled during PHP installation.
Which method to choose depends on your needs and skill level. For simple background operation and termination, Method 1 is simpler and easier to use; while Method 2 provides more granular control, but requires a deeper understanding. Remember, no matter which method, exceptions and errors of scripts should be properly handled to ensure the stability and reliability of the scripts.
The above is the detailed content of How to get PHP script to run in the background and terminate the process via Enter?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

As the digital asset market gradually matures, Bitcoin, Ethereum and Dogecoin are called the "three giants in the currency circle", attracting the attention of a large number of investors. This article will analyze their technical basis, market position, community activity and long-term potential, so as to help users understand which one is more suitable for long-term holding.

?Many people are easily influenced by market sentiment in digital currency investment, blindly following the trend but not understanding the value of the currency itself. This article will compare and analyze the core mechanisms and values ??of the three mainstream currencies, Bitcoin, Ethereum, and Dogecoin, to help readers establish rational cognition and avoid being misled by short-term fluctuations.

In the virtual asset market, Bitcoin, Ethereum and Dogecoin are the three most common mainstream currencies, and many new retail investors are often confused when faced with these three. This article will compare and analyze technical characteristics, application scenarios, market performance, development ecology and community support, etc., to help investors understand the differences between these three currencies more clearly and make more appropriate choices.

As the market conditions pick up, more and more smart investors have begun to quietly increase their positions in the currency circle. Many people are wondering what makes them take decisively when most people wait and see? This article will analyze current trends through on-chain data to help readers understand the logic of smart funds, so as to better grasp the next round of potential wealth growth opportunities.

Under the trend of Yiwu merchants accepting stablecoin payment, it is crucial to choose a reliable exchange. This article sorts out the world's top virtual currency exchanges. 1. Binance has the largest trading volume and strong liquidity, supports multiple fiat currency deposits and exits and has a security fund; 2. OKX has a rich product line, built-in Web3 wallet, and has high asset transparency; 3. Huobi (Huobi/HTX) has a long history and a huge user base, and is actively improving security and experience; 4. Gate.io has a variety of currencies, focusing on security and audit transparency; 5. KuCoin has a friendly interface, suitable for beginners and supports automated trading; 6. Bitget is known for its derivatives and order functions, suitable for users who explore diversified strategies.

Faced with the many mainstream digital assets on the market, many novice users often don’t know how to choose. Bitcoin, Ethereum and Dogecoin are three representative digital currencies, each with their own characteristics and suitable for the people. This article will help users clearly determine which currency is more suitable for their investment strategy based on currency characteristics, development potential and user comments.

Stablecoins are cryptocurrencies that are pegged to assets such as the US dollar and aim to maintain stable value. They are mainly divided into three types: fiat currency collateral, cryptocurrency collateral and algorithms. 1. Fiat currency collateral types such as USDT and USCD are supported by US dollar reserves; 2. Cryptocurrency collateral types such as DAI need to over-collateralize other currencies; 3. Algorithm relies on smart contracts to adjust supply but have high risks. The reasons why it is hotly discussed on platforms such as Douyin include: as a hedging tool when the crypto market falls, a bridge for novices to enter the crypto world, a way to obtain high-yield financial management in DeFi, and the application of low-cost cross-border payments. To obtain stablecoins, you can trade through mainstream exchanges such as Binance, Ouyi, and Huobi.

The five most valuable stablecoins in 2025 are Tether (USDT), USD Coin (USDC), Dai (DAI), First Digital USD (FDUSD) and TrueUSD (TUSD).
