我正在尝试重定向 shell 命令的输出,如下所示:
# echo here > /tmp/output
我需要在 apache 使用 exec() 函数执行的 PHP 脚本中执行此操作:
var_dump(exec('echo here > /tmp/output')); // string (0) "", no file created
上述命令不创建文件并返回退出代码 0。
我可以验证 PHP 是否能够使用 exec 执行命令,如下所示:
var_dump(exec('echo here')); // string(4) "here"
我已经尝试从以 apache 用户身份运行的 php shell 中执行此代码,并且它有效:
# su -s /bin/bash -c 'php -a' apache
php > var_dump(exec('echo here > /tmp/output')); // file is created
我试过重定向 stderr 和 stdout:
var_dump(exec('echo here 2>&1 /tmp/output')); // string(0) "", no file created
最后,我尝试将 stderr 从整个命令重定向回 exec():
var_dump(exec('echo here > /tmp/output 2>&1')); // string(0) "", no file created
根据上述步骤,在我看来问题一定与调用 php 的 apache 有关,因为它以 apache 用户身份从 php shell 运行时运行良好。
非常感谢任何帮助!
最佳答案
我想出了我的问题。问题是 apache 被配置为使用私有(private)临时目录:
PrivateTmp= Takes a boolean argument. If true, sets up a new file system namespace for the executed processes and mounts private /tmp and /var/tmp directories inside it, that are not shared by processes outside of the namespace. This is useful to secure access to temporary files of the process, but makes sharing between processes via /tmp or /var/tmp impossible. All temporary data created by service will be removed after service is stopped. Defaults to false.
因此,我在错误的位置查找脚本的输出。
关于php - 使用 PHP 的 exec() 函数重定向 shell 命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768521/