Home php教程 php手册 Forker 可以让 php-cli 进程借助 nohup 以守护进程的方式运行。

Forker 可以让 php-cli 进程借助 nohup 以守护进程的方式运行。

Jun 06, 2016 pm 07:39 PM
nohup Can process

Forker可以让php-cli进程借助nohup以守护进程的方式运行。这个Forker仅仅是让进程成为守护进程,不会复制父进程的内存。 无 ?php// 运行实例,fork 10 个进程,每个进程输出一行 Im a worker ,并保存在 /tmp/forker.log 中:// CLI命令: php Forker.php 10/

Forker 可以让 php-cli 进程借助 nohup 以守护进程的方式运行。这个 Forker 仅仅是让进程成为守护进程,不会复制父进程的内存。
<?php

// 运行实例,fork 10 个进程,每个进程输出一行 Im a worker ,并保存在 /tmp/forker.log 中:
// CLI命令: php Forker.php 10
/*
if (empty($argv[1])) {
    echo "Im a worker\n";
    sleep(10);
    exit();
} else {
    $forker = new Forker('/tmp/forker.log');
    $forker->fork($forker->findCommand('php') . ' ' . __FILE__, (int)$argv[1] <= 0 ? 10 : (int)$argv[1]);
}
*/

/**
 * Forker 可以让 php-cli 进程借助 nohup 以守护进程的方式运行。
 * 这个 Forker 仅仅是让进程成为守护进程,不会复制父进程的内存。
 */
class Forker {
    
    private $nohub = '/usr/bin/nohup';
    private $out   = '/tmp/forker.log';
    
    /**
     * @param string $output 输出文件的路径。进程的标准输出将重定向到此文件
     * @throws \RuntimeException
     */
    public function __construct($output = '') {
        if (false !== ($nohup = $this->findCommand('nohup'))) {
            $this->nohub = $nohup;
        }
        if (!is_executable($this->nohub)) {
            throw new \RuntimeException('nohup not excutable');
        }
        if ($output) {
            $this->setOutput($output);
        }
    }
    
    /**
     * 设置输出文件的路径。进程的标准输出将重定向到此文件
     * @param string $file
     * @return \Forker
     * @throws \RuntimeException
     */
    public function setOutput($file) {
        if (!is_file($file)) {
            $dir = dirname($file);
            if ((!is_dir($dir) && !mkdir($dir, 0755, true)) || !is_writable($dir)) {
                throw new \RuntimeException('output is not writable, can not create output');
            }
        } else if (!is_writable($file)) {
            throw new \RuntimeException('output is not writable');
        }
        $this->out = $file;
        return $this;
    }
    
    /**
     * 获取输出文件的路径
     * @return string
     */
    public function getOutput() {
        return $this->out;
    }
    
    /**
     * 执行命令
     * @param string $command 命令。命令中的文件参数需要使用绝对路径
     * @param int $forks fork的进程数
     */
    public function fork($command, $forks = 1) {
        for ($i = 0; $i < $forks; ++$i) {
            $this->execute($command);
        }
    }
    
    /**
     * 根据当前环境查找命令的绝对路径
     * @param string $name
     * @return boolean
     */
    public function findCommand($name) {
        $file = trim(exec("which {$name}"));
        if (is_file($file) && is_executable($file)) {
            return $file;
        }
        return false;
    }
    
    /**
     * 执行命令,成功返回 true,失败返回 false
     * @param string $command
     * @return boolean
     */
    private function execute($command) {
        $lines = [];
        $code  = 0;
        exec("{$this->nohub} {$command} >> {$this->out} 2>&1 &", $lines, $code);
        if (0 !== (int)$code) {
            file_put_contents($this->out, "fork {$command} FAILD[{$code}]:\n" . implode("\n", $lines) . "\n", FILE_APPEND);
            return false;
        }
        file_put_contents($this->out, "fork {$command} OK\n", FILE_APPEND);
        return true;
    }
    
}
Copy after login
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)

Explain what the explorer.exe process is Explain what the explorer.exe process is Feb 18, 2024 pm 12:11 PM

What process is explorer.exe? When we use the Windows operating system, we often hear the term "explorer.exe". So, are you curious about what this process is? In this article, we will explain in detail what process explorer.exe is and its functions and effects. First of all, explorer.exe is a key process of the Windows operating system. It is responsible for managing and controlling Windows Explorer (Window

What is the process of com surrogate? What is the process of com surrogate? Sep 14, 2022 pm 02:56 PM

"com surrogate" is the process of "C:\Windows\System32\dllhost.exe"; when this process occurs, it usually means that the "COM+" component stops working. This process takes up a lot of space and even does not respond directly. This is because the computer is loading the file icon. Sometimes a problem occurs, causing the computer to become stuck. You can solve the stuck problem in the computer properties settings.

What kind of process is ccsvchst.exe? What kind of process is ccsvchst.exe? Feb 19, 2024 pm 11:33 PM

ccsvchst.exe is a common process file that is part of the Symantec Endpoint Protection (SEP) software, and SEP is an endpoint protection solution developed by the well-known network security company Symantec. As part of the software, ccsvchst.exe is responsible for managing and monitoring SEP-related processes. First, let’s take a look at SymantecEndpointProtection(

How to properly kill zombie processes in Linux How to properly kill zombie processes in Linux Feb 19, 2024 am 10:40 AM

In Linux systems, zombie processes are special processes that have been terminated but still remain in the system. Although zombie processes do not consume many resources, if there are too many, they may cause system resource exhaustion. This article will introduce how to correctly remove zombie processes to ensure the normal operation of the system. 1Linux zombie process After the child process completes its task, if the parent process does not check the status in time, the child process will become a zombie process. The child process is waiting for confirmation from the parent process, and the system will not recycle it until it is completed. Otherwise, the zombie process will continue to hang in the system. To check whether there are zombie processes in the system, you can run the command top to view all running processes and possible zombie processes. The result of the ‘top’ command can be seen from the figure above in Linux.

Detailed explanation of Linux process priority adjustment method Detailed explanation of Linux process priority adjustment method Mar 15, 2024 am 08:39 AM

Detailed explanation of the Linux process priority adjustment method. In the Linux system, the priority of a process determines its execution order and resource allocation in the system. Reasonably adjusting the priority of the process can improve the performance and efficiency of the system. This article will introduce in detail how to adjust the priority of the process in Linux and provide specific code examples. 1. Overview of process priority In the Linux system, each process has a priority associated with it. The priority range is generally -20 to 19, where -20 represents the highest priority and 19 represents

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

How to shut down after running nohup command How to shut down after running nohup command Mar 18, 2024 pm 03:00 PM

Four methods: Find the process ID (PID) and kill the process using the &quot;kill&quot; command; kill all &quot;nohup&quot; processes using the &quot;killall&quot; command (use with caution); check the &quot;nohup.out&quot; file for relevant information. Through these methods, users can effectively shut down the tasks executed in the background by the &quot;nohup&quot; command.

Can I delete the downloads folder? Can I delete the downloads folder? Feb 19, 2024 pm 03:38 PM

Can downloads be deleted? In recent years, with the advent of the digital age, more and more digital products and services have appeared in our lives. What follows is that our demand for digital content is increasing day by day. In our daily life and work, we often need to download a variety of files, such as documents, pictures, audios, videos, etc. These downloaded files are usually saved in a folder called "downloads". However, over time we often find that,&quot;

See all articles