将字符串从c ++传递到php脚本

时间:2014-11-25 10:51:57

标签: php c++

我试图在php脚本和c ++程序之间传递参数。 我的php脚本看起来像这样

<?php
    $ip = $_GET["q"];
    $array = str_getcsv($ip);
    foreach($array as $line){
        exec("./a.exe", $line, $output);
        echo $output;
    }
?>

然后我希望我的c ++程序给我一个字符串(但我真的不知道怎么做),你可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

不确定你是否以正确的方式解决这个问题...但是要回答你的问题(获得一个由可执行文件发出的字符串),这真的很简单:

int main (int argc, char **argv)
{
    printf("This is a line\n");
    puts("Another line");
    stc::cout << "Last bit";
    return 0;
}

上面的代码,编译时可以通过exec执行。可以找到函数的签名in the docs

string exec ( string $command [, array &$output [, int &$return_var ]] )

告诉你它返回一个字符串(是命令输出的最后一行),将一个数组(代表每行输出)分配给第二个参数,退出代码分配给第三个参数,所以:

$last = exec('./a.exe', $full, $status);
if ($status != 0) {
    echo 'Something didn\'t go quite right';
} else {
    echo 'Last line of output was: ', $last, PHP_EOL,
         'The full output looked like this: ', PHP_EOL,
         implode(PHP_EOL, $full);
}

要对正在运行的程序启用实际的互动,您必须放弃execshell_execpassthru以及其中任何一项功能。他们只是不能胜任这份工作。你真正想要的是the proc_open function之类的东西。这样,您就可以访问程序使用的stderrstdinstdout个流,并写入stdin,有效地与流程进行交互。

根据文档中给出的第一个示例,这值得一试:

$descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("file", "/tmp/error-output.txt", "a")
);

$process = proc_open('./a.exe', $descriptorspec, $pipes);
if (!is_resource($process))
    exit(1);//error
foreach ($array as $line) {
    fwrite($pipes[0], $line."\n");//added the EOL, just in case
    fflush($pipes[0]);//flush
    usleep(100);//wait for a bit
    //unsure about this bit, though, perhaps fread is a better choice
    $output = stream_get_contents($pipes[1]);//get output
    fflush($pipes[0]);//reminds me a bit of fflush(stdin) though. So I'd probably leave this out
}
array_map('fclose', $pipes);//close streams
proc_close($process);

看看这是否适合您,查看文档,并找到一些proc_open示例。前段时间,我编写了一个自动重复命令的PHP脚本,直到将某些内容写入stderr流。我已将代码放在github上,因此可能值得一看,我也链接到来自this related question的来源

相关问题