How to invoke/start a Process in PHP and kill it using Process ID

  1. **Getting Correct Process ID:-  
  2. <?php  
  3. //Get Operating System  
  4. $OperatingSystem = php_uname('s');  
  5. if($OperatingSystem == "Windows NT") {  
  6. //**Works only for PHP 4 and above. proc_get_status() does not return correct PID so  
  7. //work around is used as shown below..  
  8. $descriptorspec = array (  
  9. 0 => array("pipe""r"),  
  10. 1 => array("pipe""w"),  
  11. );  
  12.   
  13. //proc_open — Execute a command  
  14. //'start /b' runs command in the background  
  15. if ( is_resource$prog = proc_open("start /b " . $runPath$descriptorspec$pipes$startDir, NULL) ) )  
  16. {  
  17. //Get Parent process Id  
  18. $ppid = proc_get_status($prog);  
  19. $pid=$ppid['pid'];  
  20. }  
  21. else  
  22. {  
  23. echo("Failed to execute!");  
  24. exit();  
  25. }  
  26. $output = array_filter(explode(" ", shell_exec("wmic process get parentprocessid,processid | find \"$pid\"")));  
  27. array_pop($output);  
  28.   
  29. //Process Id is  
  30. $pid = end($output);  
  31. }  
  32. else if($OperatingSystem == "Linux") {  
  33.   
  34. //**Works only for PHP 4 and above. proc_get_status() does not return correct PID so  
  35. //work around is used as shown below..  
  36. $descriptorspec = array (  
  37. 0 => array("pipe""r"),  
  38. 1 => array("pipe""w"),  
  39. );  
  40.   
  41. //proc_open — Execute a command  
  42. //'nohup' command line-utility will allow you to run command/process or shell script that can continue running in the background  
  43. if (is_resource($prog = proc_open("nohup " . $runPath$descriptorspec$pipes$startDir, NULL) ) )  
  44. {  
  45. //Get Parent process Id   
  46. $ppid = proc_get_status($prog);  
  47. $pid=$ppid['pid'];  
  48.   
  49. //Process Id is  
  50. $pid=$pid+1;  
  51.   
  52. }  
  53. else  
  54. {  
  55. echo("Failed to execute!");  
  56. exit();  
  57. }  
  58. }  
  59. ?>  
  60.   
  61.   
  62. ** To Kill Windows or Linux process:-  
  63.   
  64. <?PHP  
  65. $OperatingSystem = php_uname('s');   
  66. if($OperatingSystem == "Windows NT") {  
  67. //'F' to Force kill a process  
  68. exec("taskkill /pid $pid /F");  
  69. }  
  70. else if($OperatingSystem == "Linux") {  
  71. exec("kill -9 $pid");  
  72. }  
  73.   
  74. ?>