我建立了一個範例,示範如何透過訊息佇列與以 C 語言編寫的程式進行通訊。首先執行 C 程式(它會建立佇列),然後執行 PHP 腳本。
C 程式碼編譯方式: gcc -std=c99 -o test_queue test_queue.c
test_queue.c
/**
* 使用 PHP 和 C 程式使用 System V 訊息佇列的範例。
* 這是一個簡單的伺服器,它會建立訊息佇列並從中接收訊息。
* 基於 Beej's Guide to Unix IPC
* 作者:Jan Drazil, <qeekin at gmail dot com>
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
/* 接收訊息的緩衝區結構 */
struct php_buf {
long mtype;
char msg[200];
};
int main(void)
{
struct php_buf buf;
int msqid;
key_t key;
/* 產生金鑰(/var/www/index.php 必須是可存取的檔案) */
if((key = ftok("/var/www/index.php", 'G')) == -1) {
perror("ftok");
exit(EXIT_FAILURE);
}
/* 建立訊息佇列 */
if((msqid = msgget(key, 0666 | IPC_CREAT)) == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}
printf("準備從 PHP 接收字串!\n");
/* 接收訊息 */
if(msgrcv(msqid, &buf, sizeof(buf.msg)-1, 0, 0) == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}
/* 消除區段錯誤 */
buf.msg[199] = '\0';
printf("從 PHP 接收: %s\n", buf.msg);
/* 銷毀訊息佇列 */
if(msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
test_queue.php
<?php
if(($key = ftok("/var/www/index.php", "G")) == -1)
die("ftok");
if(!msg_queue_exists($key))
die("訊息佇列不存在");
if(($msqid = msg_get_queue($key)) === FALSE)
die("msg_get_queue");
echo "正在將文字傳送到訊息佇列。\n";
if(!msg_send($msqid, 12, "Hello from PHP!\0", false))
die("msg_send");
echo "完成"
?>