note 54803 added to function.shell-exec
| From: | jesuse dot gonzalez at venalum dot com dot ve | Date: | Fri, 15 Jul 2005 11:34:18 +0000 |
| Subject: | note 54803 added to function.shell-exec | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-92021@lists.php.net to get a copy of this message | ||
Here is an example of how you can execute a command in background an get the Process ID created by
*NIX, for future reference or monitoring.
<?php
//Run linux command in background and return the PID created by the OS
function run_in_background($Command, $Priority = 0)
{
if($Priority)
$PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
else
$PID = shell_exec("nohup $Command > /dev/null & echo $!");
return($PID);
}
?>
There is also a trick which I use to track if the background task is running using the returned PID
<?php
//Verifies if a process is running in linux
function is_process_running($PID)
{
exec("ps $PID", $ProcessState);
return(count($ProcessState) >= 2);
}
?>
I commonly use both functions in combination to batch copy big mysql tables in background and wait
for the copy process to finish sending chunks to the client browser in the following way:
<?php
$CopyTaskPid = run_in_background("mysql --user=backup_user --password=backup_user_password
--execute='INSERT INTO
backup-db.table SELECT * FROM
online-db.table'", "+20");
while(is_process_running($CopyTaskPid))
{
echo ".";
ob_flush(); flush();
sleep(2);
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.shell-exec.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54803
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54803&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54803&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54803&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54803&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54803&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54803&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54803&report=yes
Search -- http://master.php.net/manage/user-notes.php