user1504222
user1504222

Reputation: 267

Detect running process (and start if not run) under windows

Here is a code I use to check if process is running under windows, in this case calc.exe

I'm trying to start calc.exe if this one not figure out in task list.

If calc.exe is not started, is opened when run php script, but page remain in a loop until i close calc.exe.

Where do I wrong?

Help is appreciated.

// START SHOW TASKLIST
// Get Tasklist
exec("tasklist 2>NUL", $task_list);

//print_r($task_list);
echo '<pre>'; print_r($task_list); echo '</pre>';
// END SHOW TASKLIST


// Service running
$kill_pattern = '~(calc)\.exe~i';

// Create array
$task_list = array();

exec("tasklist 2>NUL", $task_list);

foreach ($task_list AS $task_line) {
  if (preg_match($kill_pattern, $task_line, $out)) {
    echo "=> Detected: ".$out[1]."\n   !\n";
    $is_running = '1';  
    break; 
  }
}

if ($is_running == '1') {
  echo 'Nothing to do';
  exit; 
} else {
  // open calc.exe
  exec("calc.exe");
  exit;
}

Upvotes: 1

Views: 697

Answers (1)

Hid Dencum
Hid Dencum

Reputation: 592

Please use this code to avoid script hang up

Change

exec(calc.exe);

With

pclose(popen('start /B cmd /C "calc.exe >NUL 2>NUL"', 'r'));

Upvotes: 1

Related Questions