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

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;
    }
    
}
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.