PHP通过双向管道与C通信

14 篇文章 0 订阅

上个月的一篇博客进程与系统调用、进程间通信–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。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值