Featured image of post PHP进程间通信

PHP进程间通信

什么是进程间通信?

进程间通信(英语:Inter-Process Communication,简称IPC),指至少两个进程或线程间传送数据或信号的一些技术或方法。

有名管道:

面向字节流、自带同步互斥机制、半双工,单向通信,两个管道实现双向通信。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public function actionPipeRecv()
{
    $msgFilename = '/fifo-msg.pipe';
    while(true) {
        $fMsg = fopen($msgFilename, 'r');
        var_dump(fgets($fMsg));
        fclose($fMsg);
        sleep(2);
    }
}


/**
 * php 管道
 * 面向字节流、自带同步互斥机制、半双工,单向通信,两个管道实现双向通信。
 * @param $txt
 */
public function actionPipeSend($txt)
{
    $msgFilename = '/fifo-msg.pipe';
    if (!file_exists($msgFilename)) {
        posix_mkfifo($msgFilename, 0664);
    }

    for($i = 0; $i < 100; $i++) {
        $f = fopen($msgFilename, 'w');
        $msg = sprintf("n: %d; msg: %s;", $i, $txt);
        fwrite($f, $msg);
        fclose($f);
    }
}

消息队列

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * 向消息队列写入数据
 */
public function actionQueuePush()
{
    $file = \Yii::getAlias('@console') . '/runtime/test-queue';
    if (!file_exists($file)) {
        touch($file);
    }

    $key = ftok($file, 'H');
    $queue = msg_get_queue($key);
    for($i = 0; $i < 10; $i++) {
        msg_send($queue, 1, $i * $i);
    }
}

/**
 * 从消息队列接收数据
 */
public function actionQueueRecv()
{
    $key = ftok(\Yii::getAlias('@console') . '/runtime/test-queue', 'H');
    $queue = msg_get_queue($key);
    while(true) {
        msg_receive($queue, 1, $msgType, 4096, $msg, false);
        var_dump($msg);
        sleep(1);
    }
}
Built with Hugo
主题 StackJimmy 设计