我尝试通过单个php exec()调用在后台执行两个linux命令。
我的第一个命令进行一些文件备份:
cp -r ../source ../destination
第二个命令在备份完成后创建文件“ DONE.txt”:
touch ../destination/DONE.txt
此外,我基于php手册并使用以下后台exec()调用:
exec('bash -c "exec nohup setsid '.$twoCommands.' > /dev/null 2>&1 &"');
整个代码如下:
exec('bash -c "exec nohup setsid { cp -r ../source ../destination && touch ../destination/DONE.txt; } > /dev/null 2>&1 &"');
而且...不起作用:)但是为什么呢?
如果我仅使用一个命令:
exec('bash -c "exec nohup setsid cp -r ../source ../destination > /dev/null 2>&1 &"');
效果很好:)
答案 0 :(得分:1)
我不知道您为什么要使它变得如此复杂。 nohup
和setsid
是两个完全独立的函数,而不是您传递给exec
的参数。您甚至不需要在命令本身中调用exec
;这就是在PHP中使用exec
的意义。仅当您需要PHP脚本在exec
调用后在后台继续而不是等待其完成时,才需要输出重定向。
[root@test~]# ll
total 8
drwxr-xr-x. 2 root root 24 Jun 27 13:40 source
[root@test~]# ll source
total 0
-rw-r--r--. 1 root root 0 Jun 27 13:40 1
-rw-r--r--. 1 root root 0 Jun 27 13:40 2
[root@test~]# php -a
Interactive shell
php > exec("cp -r ./source ./destination && touch ./destination/DONE.txt");
php > exit
[root@test~]# ll destination/
total 0
-rw-r--r--. 1 root root 0 Jun 27 13:44 1
-rw-r--r--. 1 root root 0 Jun 27 13:44 2
-rw-r--r--. 1 root root 0 Jun 27 13:44 DONE.txt
[root@test~]#