[英]PHP script stuck on exec even after running command in backgroud on Windows
我想要一個可以執行程序的php腳本,如果它在2秒鍾內未完成執行,則終止它。 我正在使用Windows。 我嘗試了以下代碼:
exec("start /B program.exe");
sleep(2);
exec('taskkill /F /IM "program.exe"');
只要未將program.exe
執行完畢,腳本就停留在第一個exec
語句上,這似乎不起作用。 我不知道如何解決此問題。
是的, exec()
將阻塞直到執行完成。 這個問題對於如何使用超時exec()
有很好的答案。 我認為這可能最適合您。 為了完整起見,我將代碼發布在這里(但我不能功勞!):
/**
* Execute a command and return it's output. Either wait until the command exits or the timeout has expired.
*
* @param string $cmd Command to execute.
* @param number $timeout Timeout in seconds.
* @return string Output of the command.
* @throws \Exception
*/
function exec_timeout($cmd, $timeout) {
// File descriptors passed to the process.
$descriptors = array(
0 => array('pipe', 'r'), // stdin
1 => array('pipe', 'w'), // stdout
2 => array('pipe', 'w') // stderr
);
// Start the process.
$process = proc_open('exec ' . $cmd, $descriptors, $pipes);
if (!is_resource($process)) {
throw new \Exception('Could not execute process');
}
// Set the stdout stream to none-blocking.
stream_set_blocking($pipes[1], 0);
// Turn the timeout into microseconds.
$timeout = $timeout * 1000000;
// Output buffer.
$buffer = '';
// While we have time to wait.
while ($timeout > 0) {
$start = microtime(true);
// Wait until we have output or the timer expired.
$read = array($pipes[1]);
$other = array();
stream_select($read, $other, $other, 0, $timeout);
// Get the status of the process.
// Do this before we read from the stream,
// this way we can't lose the last bit of output if the process dies between these functions.
$status = proc_get_status($process);
// Read the contents from the buffer.
// This function will always return immediately as the stream is none-blocking.
$buffer .= stream_get_contents($pipes[1]);
if (!$status['running']) {
// Break from this loop if the process exited before the timeout.
break;
}
// Subtract the number of microseconds that we waited.
$timeout -= (microtime(true) - $start) * 1000000;
}
// Check if there were any errors.
$errors = stream_get_contents($pipes[2]);
if (!empty($errors)) {
throw new \Exception($errors);
}
// Kill the process in case the timeout expired and it's still running.
// If the process already exited this won't do anything.
proc_terminate($process, 9);
// Close all streams.
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $buffer;
}
編輯
proc_open()
的“ exec”部分可能無法在Windows上運行,但可能沒有必要。
您是否正在使用php cli(命令行)執行此操作? 以管理員身份打開命令提示符 。
為了不被等待程序阻塞而關閉程序的打開過程 。
php myscript.php
pclose(popen("start /B program.exe", "r"));
sleep(2);
exec('taskkill /F /IM program.exe');
exit(0);
將exec開始放入一個單獨的腳本並使用exec
觸發該腳本也可以
exec()
手冊頁的第一條注釋顯示了一個非常簡單的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.