2014-11-25 118 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

相關問題