2

pcntl_signal別のプロセスから送信されたシグナルを受信できないという問題があります。新しいプロセスをフォークし、2 つのバックグラウンド スレッドを起動し、停止信号 (SIGUSR1) を受信するまでコントローラー (メイン) スレッドをループするスクリプトがありますが、信号は受信されません。これが私のスレッドコードです(デモ目的でループにログインするだけです)。

declare(ticks = 100);

class Background1 extends Thread {

    public function __construct() {

    }

    public function run() {

        echo "Starting Background 1 thread";

        while( $this->running ) {

            echo "Background 1 looping...\n";

            sleep(5);
        }

        echo "Exiting Background 1 thread";
    }

    public function play() {
        $this->running = true;
        $this->start();
    }

    public function stop() {
        $this->notify();
        $this->join();
    }
}

class Background2 extends Thread {

    public function __construct() {

    }

    public function run() {

        echo "Starting Background 2 thread";

        while( $this->running ) {

            echo "Background 2 looping...\n";

            sleep(5);
        }

        echo "Exiting Background 2 thread";
    }

    public function play() {
        $this->running = true;
        $this->start();
    }

    public function stop() {
        $this->running = false;
        $this->join();
    }
}

class ControllerThread {

    function __construct() {

    }

    function handleSignal($signo) {

        echo "Received signal $signo";

        switch ($signo) {
            case SIGUSR1:
                $this->running = true;
                break;

             default:
                // handle all other signals
        }
    }

    public function run() {

        pcntl_signal(SIGUSR1, array(&$this, "handleSignal"), true);

        $this->running = true;

        while( $this->running ) {

            echo "Starting controller loop";

            $background1 = new Background1;
            $background2 = new Background2;

            $background1->play();
            $background2->play();

            while( $this->running ) {

                echo "Controller looping...";

                sleep(5);

                pcntl_signal_dispatch();
            }

            $background1->stop();
            $background2->stop();

            echo "Exiting controller loop";
        }
    }
}

date_default_timezone_set('Europe/London');

$child_pid = pcntl_fork();
if ($child_pid) {
    pcntl_waitpid($child_pid, $status);
    $child_pid = posix_getpid();
    echo "PID running: $child_pid";
    exit;
}

echo "Starting main app thread";

$controller = new ControllerThread();
$controller->run();

echo "Exiting main app thread";

別のプロセスでは、次のように他のプロセスにシグナルを送ります。

posix_kill($pid, SIGUSR1); // $pid being the $child_pid from the other process.

シグナル ハンドラが呼び出されることはありません。

私は何を間違っていますか?

4

1 に答える 1