1
<?php

$dira = dirname(__DIR__);

$output = exec($dira . "\\htdocs\\PocketMine-MP-stable\\start.cmd");

echo $output

?>

I need to find a way to kill the process after starting it with exec() this is for a

sweetpeps
  • 23
  • 2
  • 6

2 Answers2

2

exec returns Once the process terminates. So after exec you cannot kill the process as it Is no longer running. You have to run the process with proc_open And you can then kill it with proc_terminate.

EDIT: Actualy you can have exec return earlier if you redirect output of the command to a file And append & to the end of the command (or use nohup; Linux only maybe) so it runs in background. But getting the pid to send kill signal to it is only possible by name And that Is not very reliable

slepic
  • 641
  • 4
  • 11
-1

You may use posix_kill to kill a process with identifier pid.

Usage

//...
exec($dira . "\\htdocs\\PocketMine-MP-stable\\start.cmd", $output);
$pid = (int)$output[0];
$killed = posix_kill(int $pid , int $sig);

You should see all signals and their codes in your system using: kill -l

Check my Repl example

Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39
  • How do they get the pid? – Nigel Ren Feb 01 '20 at 07:49
  • "If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable." check doc : https://www.php.net/manual/en/function.exec.php – Foued MOUSSI Feb 01 '20 at 08:09
  • Not sure if the return status is the pid though. – Nigel Ren Feb 01 '20 at 08:10
  • [Related.](https://stackoverflow.com/questions/1470910/invoke-external-shell-script-from-php-and-get-its-process-id) Aka, what's in this answer is probably not enough. – Jeto Feb 01 '20 at 08:21
  • I gave it a try here https://repl.it/@FMOUSSI/Killing-a-process-with-PHP-after-exec – Foued MOUSSI Feb 01 '20 at 08:32
  • Try adding `echo $pid.PHP_EOL;` and see what it is. – Nigel Ren Feb 01 '20 at 08:56
  • This Is nonsense. Even if you could get pid from exec, it would be invalidated when exec returns. – slepic Feb 01 '20 at 09:10
  • Actualy you can have it return earlier if you redirect output of the command to a file And append `&` to the end of the command (Linux only maybe) So it runs in background. Getting the pid tho, Is only possible by name And that Is not reliable. – slepic Feb 01 '20 at 09:25
  • `posix_kill` won't kill a process if it is originated from a browser request aka apache process. – H Aßdøµ May 06 '22 at 18:12