1

I have this php script that will run wget's fork processes each time this is called with the & :

wget http://myurl?id='.$insert_id .' -O ./images/'. $insert_id.' > /dev/null 2>&1 &

But how I can check if there is already a wget proces in progress and if there is one, don't run another one ?

Tatu Bogdan
  • 586
  • 2
  • 10
  • 27
  • You'll need the process ID: http://stackoverflow.com/a/1471320/561309 then you can check if that process is still running or not – laurent Feb 28 '17 at 15:29
  • 2
    execute **ps -ef | grep wget** and find out. I have a lot longer and more legitimate solution if you need more info. – Dimi Feb 28 '17 at 15:43
  • Possible duplicate of [Checking if process still running?](http://stackoverflow.com/questions/3111406/checking-if-process-still-running) – jww Mar 01 '17 at 00:42

1 Answers1

0

This code is used to control running process (which in my case is php script).

Feel free to take out parts that you need and use them as you please.

class Process
{
  private $processName;
  private $pid;

  public $lastMsg;

  public function __construct($proc)
  { 
    $this->processName = $proc;
    $this->pid = 0;
    $this->lastMsg = "";
  }

  private function update()
  { 
    $output = array();
    $cmd = "ps aux | grep '$this->processName' | grep -v 'grep' | awk '{ print $2; }' | head -n 1";
    exec($cmd, $output, $rv);

    if ($rv == 0 && isset($output[0]) && $output[0] != "")
      $this->pid = $output[0];
    else
      $this->pid = false;

    return;
  }

  public function start()
  { 
    // if process isn't already running,
    if ( !$this->is_running() )
    { 
      // call exec to start php script
      $op = shell_exec("php $this->processName &> /dev/null & echo $!");

      // update pid
      $this->pid = $op;
      return $this->pid;
    }
    else
    { 
      $this->lastMsg = "$this->processName already running";
      return false;
    }
  }
  public function is_running()
  {
    $this->update();

    // if there is no process running
    if ($this->pid === false)
    {
      $this->lastMsg = "$this->processName is not running";
      return false;
    }
    else
    {
      $this->lastMsg = "$this->processName is running.";
      return true;
    }
  }

  public function stop()
  {
    $this->update();

    if ($this->pid === false)
    {
      return "not running";
    }
    else
    {
      exec('kill ' . $this->pid, $output, $exitCode);
      if ($exitCode > 0)
        return "cannot kill";
      else
        return true;
    }
  }

}
Dimi
  • 1,255
  • 11
  • 20