Autarchy of the Private Cave

Tiny bits of bioinformatics, [web-]programming etc

  • Exits

  • Categories

  • Archives

  • Tags list

    • Blog sponsors

    • Exits

    • Visitors’ track

      Locations of visitors to this page

    Executing and checking background shell process from PHP

    23rd May 2007

    Found a nicely illustrated method for running a background shell command from PHP and continuously checking if the process is still running.

    Here's sample code without explanations:

    PHP:
    1. function run_in_background($Command, $Priority = 0)
    2. {
    3.  if($Priority)
    4.   $PID = shell_exec("nohup nice -n $Priority $Command 2> /dev/null & echo $!");
    5.  else
    6.   $PID = shell_exec("nohup $Command 2> /dev/null & echo $!");
    7.  return($PID);
    8. }
    9.  
    10. function is_process_running($PID)
    11. {
    12.  exec("ps $PID", $ProcessState);
    13.  return(count($ProcessState)>= 2);
    14. }

    To run something like hmmsearch from the HMMER package, you’d do this:

    PHP:
    1. echo("Running hmmsearch. . .")
    2. $ps = run_in_background("hmmsearch $hmmfile $fastafile> $outfile");
    3. while(is_process_running($ps))
    4. {
    5.  echo(" . ");
    6.  ob_flush();flush();
    7.  sleep(1);
    8. }

    • Delicious
    • Google Bookmarks
    • Yahoo Bookmarks
    • Windows Live Favorites
    • Technorati Favorites
    • Digg
    • Slashdot
    • StumbleUpon
    • Read It Later
    • Twitter
    • Share/Bookmark

    2 Responses to “Executing and checking background shell process from PHP”

    1. Joe Says:

      function is_process_running($PID)
      {
      exec("ps $PID", $ProcessState);
      return(count($ProcessState)>= 2);
      }

      IMO, it is more elegant to check for the exit code instead.

    2. Bogdan Says:

      Joe,

      how would you do that, given the example application above? I see no way of getting exit status from a process which has finished.

    Leave a Reply

    XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>