上个月的一篇博客进程与系统调用、进程间通信–Head First C读书笔记介绍了C语言的进程通信,今天介绍下PHP通过双向管道与C通信。
先看看C的代码
#include <stdio.h>
int main()
{
char msg[20];
fgets(msg, sizeof(msg), stdin);
printf("%s", msg);
return 0;
}
很简单逻辑,就是接收标准输入然后再输出到屏幕。编译、执行下
[root@Slave1 first_chapter]# gcc test.c -o test
[root@Slave1 first_chapter]# ./test
hello world
hello world
接下来看看PHP的代码
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // 标准输入,子进程从此管道中读取数据
1 => array("pipe", "w") // 标准输出,子进程向此管道中写入数据
);
$handle = proc_open(
'/var/www/html/c/c_pointer/first_chapter/test', // C代码编译后程序的绝对地址
$descriptorspec,
$pipes
);
if (!isset($argv[1]))
die("failure");
fwrite($pipes['0'], $argv[1] . "\n");
echo fgets($pipes[1]);
fclose($pipes['0']);
fclose($pipes['1']);
proc_close($handle);
上面的PHP代码中使用proc_open
打开一个进程,调用C程序。同时返回一个双向管道pipes
数组,PHP向$pipe['0']
中写数据,从$pipe['1']
中读数据。
运行下
[root@Slave1 first_chapter]# php test.php
failure[root@Slave1 first_chapter]# php test.php hello
hello
[root@Slave1 first_chapter]# php test.php hellosdfasfas
hellosdfasfas
[root@Slave1 first_chapter]# php test.php hellosdfasfas world
hellosdfasfas
[root@Slave1 first_chapter]# php test.php "hellosdfasfas world"
hellosdfasfas world[root@Slave1 first_chapter]#
有了这个,可以做很多事情,如PHP中运算密集、内存消耗大的可以交给C来做,当然了也可以借用此思想,与其他语言通信,如Go。