又來了一個辦法,而不需要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";
}
爲簡潔起見,省略了錯誤處理。但請記住,在系統編程中應該謹慎處理任何函數返回值。
你救了我的命;)謝謝。只要我回到我的電腦,我就會接受答案 –
不客氣!我以前也不知道。 – hek2mgl