2011-10-25 20 views
1

我使用popenRWE從http://www.jukie.net/bart/blog/popenRWE,使下面C++ popen方法來運行PHP

int pipes[3]; 
int pid; 
const char *const args[] = { 
    "php ", 
    NULL 
}; 
pid = popenRWE(pipes, args[0], args); 

char *cmd = "<?php echo 'hello world';?> "; 
cout << "write: " << write(pipes[0], cmd, strlen(cmd)) << endl; 
cout << "err: " << errno << endl; 

char res[100]; 
cout << "read: " << read(pipes[1], res, 100) << endl; 
cout << "result: " << res << endl; 

劇本時,我使用cat命令,它的工作原理,其輸入是輸出中(這是貓做什麼),但使用php讀取爲空。我已確認已安裝了PHP和我的道路上通過直接在控制檯上運行

echo "<?php echo 'hello world';?>" | php

,並得到了輸出。有人可以請建議或幫助此代碼?提前致謝。

+0

不'popenRWE'返回一個有效ID(即不是一個錯誤)?在'$ PATH'中是'php'嗎? –

回答

1

有三個問題與您的代碼:

  • 沒有名爲"php "可執行文件。只有"php"(注意沒有空間)。這是行不通的原因是因爲popenRWE使用execvp它不會啓動一個shell來執行該命令,但它期望您要執行的二進制文件的文件名(儘管它在$PATH中進行搜索)。
  • 您應該在編寫數據之後closestdin文件句柄,否則您可能需要無限期地等待輸出寫入。
  • 此外,你應該等待php進程完成使用waitpid,否則你可能會「失去」一些輸出。

把它包起來:

int pipes[3]; 
int pid; 
const char *const args[] = { 
    "php", 
    NULL 
}; 
pid = popenRWE(pipes, args[0], args); 

char *cmd = "<?php echo 'hello world', \"\\n\";?> "; 
cout << "write: " << write(pipes[0], cmd, strlen(cmd)) << endl; 
cout << "err: " << errno << endl; 
close(pipes[0]); 

// TODO: proper error handling 
int status; 
waitpid(pid, &status, 0); 

char res[100]; 
int bytesRead = read(pipes[1], res, (sizeof(res)/sizeof(char))-1); 
// zero terminate the string 
res[bytesRead >= 0 ? bytesRead : 0] = '\0'; 

cout << "read: " << bytesRead << endl; 
cout << "result: " << res << endl; 
+0

,這意味着我不能重複使用'stdin'文件句柄,因爲它在寫入後立即關閉。有沒有機會保持開放並重用它?我試圖實現的東西,因爲我在http://stackoverflow.com/questions/7844320/php-as-daemon-service中描述的PHP進程已經打開,我只是將腳本餵給進程處理程序以獲取它的輸出。 – user777305

+0

當零終止字符串 – Dani

+0

@ user777305時bytesRead = 100時,您會出現分段錯誤:您可以刷新它而不是關閉。 – Dani