PHP命令脚本生成的后台脚本打印到屏幕

I need to make a background script that is spawned by PHP command line script that echos to the SSH session. Essentially, I need to do this linux command:

script/path 2>&1 &

If I just run this command in linux, it works great. Output is still displayed to the screen, but I can still use the same session for other commands. However, when I do this in PHP, it doesn't work the same way.

I've tried:

`script/path 2>&1 &`;

exec("script/path 2>&1 &");

system("script/path 2>&1 &")

...And none of these work. I need it to spawn the process, and then kill itself so that I can free up the session, but I still want the output from the child process to print to the screen.

(please comment if this is unclear... I had a hard time putting this into words :P)

I came up with a solution that works in this case.

I created a wrapper bash script that starts up the PHP script, which in turn spawns a child script that has its output redirected to a file, which the bash script wrapper tails.

Here is the bash script I came up with:

  php php_script.php "$@"
  ps -ef | grep php_script.log | grep -v grep | awk '{print $2}' | xargs kill > /dev/null 2>&1
  if [ "$1" != "-stop" ]
  then
      tail -f php_script.log -n 0 &
  fi

(it also cleans up "tail" processes that are still running so that you don't get a gazillion processes when you run this bash script multiple times)

And then in your php child script, you call the external script like this:

exec("php php_script.php >> php_script.log &");

This way the parent PHP script exits without killing the child script, you still get the output from the child script, and your command prompt is still available for other commands.