📜 ⬆️ ⬇️

Set the execution time of the console command

It was possible once to write a script that, in the course of its work, ran through the list of video files and launched ffmpeg for each with a key that allows to get information about the file. I actually needed the playback time.

Everything would be fine, but on one file ffmpeg hung and did not think to end, but at the time of completion the php script also fell off for no apparent reason.

After a long search for a solution to this problem, a code was found that after a small rework I am ready to submit to your judgment :)
')

The main problem was that it was not possible to limit the execution time of ffmpeg.

The following code helped:

<?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 .


The code is quite simple and clear, for this reason it probably makes no sense to write a description to it.

Usage example

PsExecute ('ffmpeg -i video_file.flv', 5, 1, '/tmp/1.txt');
If ffmpeg does not complete in 5 seconds, it will be completed automatically.

Download in the archive

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


All Articles