dp9599 2017-03-14 20:30
浏览 97
已采纳

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)

  • 写回答

1条回答 默认 最新

  • dsgdg54ef4365 2017-03-15 21:03
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题