BackgroundExecutor.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. function doParentExit($errCode) {
  3. print "Done with parent\n";
  4. exit ($errCode);
  5. }
  6. function usage() {
  7. $usageStr = <<<USAGEDOC
  8. Usage:
  9. --txn-id Transaction ID
  10. --no-fork Whether to fork again
  11. --command Command to run
  12. --args Args for command ( optional )
  13. --logfile Logfile to redirect output to
  14. --help Print this help message.
  15. USAGEDOC;
  16. print $usageStr . "\n";
  17. }
  18. $shortopts = "ht:c:a:l:n";
  19. $longopts = array(
  20. "txn-id:", // Txn ID
  21. "command:", // Command to execute
  22. "args:", // Args for command
  23. "logfile:", // Log file
  24. "no-fork", // Whether to fork again - by default always forks
  25. "help", // Help - print usage
  26. );
  27. $options = @getopt($shortopts, $longopts);
  28. $txnId = "";
  29. $command = "";
  30. $args = "";
  31. $logFile = "";
  32. $doFork = TRUE;
  33. // print "Executing process " . implode (" ", $argv) . "\n";
  34. foreach ($options as $opt => $val) {
  35. if ($opt == "txn-id" || $opt == "t") {
  36. $txnId = $val;
  37. }
  38. else if ($opt == "command" || $opt == "c") {
  39. $command = $val;
  40. }
  41. else if ($opt == "args" || $opt == "a") {
  42. $args = $val;
  43. }
  44. else if ($opt == "logfile" || $opt == "l") {
  45. $logFile = $val;
  46. }
  47. else if ($opt == "no-fork" || $opt == "n") {
  48. $doFork = FALSE;
  49. }
  50. else if ($opt == "help" || $opt == "h") {
  51. usage();
  52. doParentExit (0);
  53. }
  54. else {
  55. print "Invalid option passed to script, option=" . $opt . "\n";
  56. usage();
  57. doParentExit (1);
  58. }
  59. }
  60. if ($command == "" || $txnId == "") {
  61. print "One of transaction id or command not specified\n";
  62. usage();
  63. doParentExit (1);
  64. }
  65. $execCommand = "$command $args";
  66. if ($logFile != "") {
  67. $execCommand .= " > $logFile 2>&1 ";
  68. }
  69. print "Executing $execCommand\n";
  70. if ($doFork) {
  71. $pid = pcntl_fork();
  72. if ($pid === FALSE || $pid == -1) {
  73. print "Could not fork process\n";
  74. doParentExit (1);
  75. } else if ($pid > 0) {
  76. flush();
  77. print "Background Child Process PID:$pid\n";
  78. flush();
  79. doParentExit (0);
  80. }
  81. }
  82. // in child process or if fork disabled
  83. $output = array();
  84. unset($output);
  85. $errCode = 0;
  86. exec($execCommand, $output, $errCode);
  87. exit ($errCode);
  88. ?>