2015-09-01 21 views
4

不幸的是,我發現執行外部程序的所有解決方案都不合適,所以我使用自己的實現,即在pcntl_fork之後的pcntl_exec如何從PHP調用Linux dup2?

但現在我需要將執行程序的stderr/stdout重定向到某個文件。很明顯,我應該在pcntl_fork之後使用某種dup2 Linux調用,但我在PHP中看到的唯一的dup2eio_dup2,它看起來像運行不是普通流(如stderr/stdout),而是一些異步流。

如何從PHP調用dup2或者如何在沒有它的情況下重定向std *?

同樣的問題(雖然沒有詳細說明)並沒有回答:How do I invoke a dup2() syscall from PHP ?

回答

4

又來了一個辦法,而不需要dup2。它基於this answer

$pid = pcntl_fork(); 

switch($pid) { 

    case 0: 
     // Standard streams (stdin, stdout, stderr) are inherited from 
     // parent to child process. We need to close and re-open stdout 
     // before calling pcntl_exec() 

     // Close STDOUT 
     fclose(STDOUT); 

     // Open a new file descriptor. It will be stdout since 
     // stdout has been closed before and 1 is the lowest free 
     // file descriptor 
     $new_stdout = fopen("test.out", "w"); 

     // Now exec the child. It's output goes to test.out 
     pcntl_exec('/bin/ls'); 

     // If `pcntl_exec()` succeeds we should not enter this line. However, 
     // since we have omitted error checking (see below) it is a good idea 
     // to keep the break statement 
     break; 

    case -1: 
     echo "error:fork()\n"; 
     exit(1); 

    default: 
     echo "Started child $pid\n"; 
} 

爲簡潔起見,省略了錯誤處理。但請記住,在系統編程中應該謹慎處理任何函數返回值。

+0

你救了我的命;)謝謝。只要我回到我的電腦,我就會接受答案 –

+0

不客氣!我以前也不知道。 – hek2mgl