dongli1920 2018-08-08 18:47
浏览 62

使用PHP over HTTP在退出时运行带有陷阱的后台bash

I'm trying to use PHP to trigger a bash script that should never stop running. It's not just that the command needs to run and I don't need to wait for output, it needs to continue running after PHP is finished. This has worked other times (and the question has been asked already), the difference seems to be my bash script has a trap for when it's closed.

Here is my bash script:

#!/bin/bash

set -e

WAIT=5
FILE_LOCK="$1"

echo "Daemon started (PID $$)..."

echo "$$" > "$FILE_LOCK"

trap cleanup 0 1 2 3 6 15

cleanup()
{
  echo "Caught signal..."
  rm -rf "$FILE_LOCK"
  exit 1
}

while true; do
    # do things
    sleep "$WAIT"
done

And here is my PHP:

$command = '/path/to/script.sh /tmp/script.lock >> /tmp/script.log 2>&1 &';
$lastLine = exec($command, $output, $returnVal);

I see the script run, the lock file get created, then it exits, and the trap removes the lock file. In my /tmp/script.log I see:

Daemon started (PID 55963)...
Caught signal...

What's odd is that this only happens when running the PHP via Apache. From command line it keeps running as expected.

The signal on the trap that's being caught is 0.

I've tried wrapping my command in a bash environment, like $command = '/bin/bash -c "' . addslashes($command) . '"';, also tried adding nohup to the beginning. Nothing seems to be working. Is this possible to do for a never ending script?

  • 写回答

1条回答 默认 最新

  • doukuang1950 2018-08-09 18:51
    关注

    Found the problem thanks to @lxg.

    My # do things command was giving errors, which was causing the script to exit. For some reason they were suppressed.

    When removing set -e from the beginning of my bash script I started seeing the errors output to my log file. Not sure why they didn't show up before.

    The issue was in my bash loop it was running PHP commands. Even though my bash user and Apache user are the same, for some reason they had different $PATHs. This meant that when running on command line I was using a PHP7 binary, but when Apache trigged bash commands it was using a PHP5 binary (even though Apache itself is configured to use PHP7). So the application errored out and that is what caused the script to die.

    The solution was to explicitly set the PHP binary path in my bash loop.

    I was doing this with

    BIN_PHP=$(which php)
    

    But on true command line it would return one value (/path/to/php7/bin/php) vs command line initiated by Apache (/path/to/php5/bin/php). Despite Apache being the same as a my command line user, it didn't load the ~/.bashrc which specified my correct PHP path.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)