コンソールコマンドの実行時間を設定する

作業の過程で、ビデオファイルのリストを実行し、起動されたffmpegごとに、ファイルに関する情報を取得できるキーを使用してスクリプトを作成する機会がありました。 実際に再生時間が必要でした。

すべては問題ありませんが、あるファイルではffmpegが一時停止し、終了するとは思わず、完了時にphpスクリプトも明確な理由もなく落ちました。

この問題の解決策を探し続けた結果、コードが見つかりました。少し変更した後、私はあなたの裁判所に提出する準備ができています:)


主な問題は、ffmpegランタイムを制限できないことでした。

次のコードが役に立ちました:

<?php

/**
* Run process with timeout
* @param str $command
* @param int $timeout - sec
* @param int $sleep
* @param str $file_out_put - if default value, then return true else return out of process
* @return bool or str
*/
function PsExecute($command, $timeout = 10, $sleep = 1, $file_out_put = '/dev/null' ) {

$pid = PsExec($command, $file_out_put);

if ( $pid === false ) {
return false ;
}

$cur = 0;

//
while ( $cur < $timeout ) {
sleep($sleep);
$cur += $sleep;

if ( !PsExists($pid) ) {
// , true
if ($file_out_put != '/dev/null' ) {
return file_get_contents($file_out_put);
} else {
return true ;
}
}
}

// ,
PsKill($pid);
return false ;
}

/**
* Run process in background with out buffer to file
* @param str $commandJob
* @param str $file_out_put
* @return int or false
*/
function PsExec($commandJob, $file_out_put) {
$command = $commandJob. ' > ' .$file_out_put. ' 2>&1 & echo $!' ;
exec($command ,$op);
$pid = ( int )$op[0];

if ($pid!= "" ) return $pid;

return false ;
}

/**
* If process exists then return true else return false
* @param int $pid
* @return bool
*/
function PsExists($pid) {

exec( "ps ax | grep $pid 2>&1" , $output);

while ( list(,$row) = each($output) ) {

$row_array = explode( " " , $row);
$check_pid = $row_array[0];

if ($pid == $check_pid) {
return true ;
}

}

return false ;
}

/**
* Kill process
* @param int $pid
*/
function PsKill($pid) {
exec( "kill -9 $pid" , $output);
}

?>


* This source code was highlighted with Source Code Highlighter .


このコードは非常に単純で単純なので、説明を記述することはおそらく意味がありません。

使用例

PsExecute( 'ffmpeg -i video_file.flv'、5、1、 '/tmp/1.txt');
ffmpegが5秒以内に完了しない場合、自動的に完了します。

アーカイブでダウンロード

Source: https://habr.com/ru/post/J66160/


All Articles