【问题标题】:TWO linux commands executed in background called by PHP exec() functionPHP exec() 函数在后台执行的两个 linux 命令
【发布时间】:2019-06-11 08:45:43
【问题描述】:

我尝试通过单个 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 &"');

效果很好:)

【问题讨论】:

  • 如果您不将错误重定向到/dev/null,您会看到什么错误?你确定当前目录是什么?你有权限吗?等等等等
  • 如果我只使用一个命令: exec('bash -c "exec nohup setsid cp -r ../source ../destination > /dev/null 2>&1 &"');效果很好:)

标签: php linux command-line-interface exec


【解决方案1】:

我不知道你为什么要让事情变得如此复杂。 nohupsetsid 是两个完全独立的函数,而不是传递给 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~]# 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2013-09-07
    • 2014-03-11
    • 2011-06-06
    相关资源
    最近更新 更多