2014-11-25 37 views
-1

我试图在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++程序返回我的字符串(但我真的不知道该怎么做),你可以在这方面帮助?

+0

它看起来像PHP希望有'a.exe'的标准输出。 – 2014-11-25 10:59:30

回答

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。这样,您可以访问程序使用的stderr,stdinstdout流,并写入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

相关问题