Answer the question
In order to leave comments, you need to log in
How to run a linux command in the background using php?
To run scripts on the server in the background, I usually use the nohup command. I tried to call it via exec and shell_exec without additional parameters. When running a command, the script hangs until the command is executed. Below is the command code:
exec('nohup rsync -avz -e "ssh -p 22 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" [email protected]:/original/ /destination/s_24/ && echo $? >> /destination/l_24.txt 2>&1 &');
sleep 15 &
nohup sleep 15 &
setsid sleep 15 &
nohup sleep 15 && exit &
nohup sleep 15 & exit
Answer the question
In order to leave comments, you need to log in
The most important thing to do is to redirect the stdout of commands from nohup (via > for example). Simplified example. We start printing DA in the background 10 seconds after launch without blocking the php process:
Run example:
$ date +%X
17:15:32
$ php -f test.php && date +%X && tail -F nohup.php.out
17:15:34
DA
^C
$ date +%X
17:15:45
$
nohup is a bash command that simply tells bash itself that a background process should not send a HUP signal when it shuts down.
& is also a bash feature that allows you to transfer the process to the background
The problem is that php is not bash for you and it probably keeps track of the state of the process it launched.
Try using setsid .
Unlike nohup, this is a full-fledged program that launches the program specified as an argument in a separate session. Once the target program is started, setsid exits. This should "release" php almost instantly.
Once again I checked everything and wrote a crutch ... I consider the problem unresolved =(
Итоговые выводы:
Чтобы запустить команду асинхронно, нужно:
1. Перенаправить основной поток вывода из консоли (в /dev/null или файл)
2. Использовать после команды символ &
nohup и другие дополнительные команды не нужны
В моем случае это всё не сработало. Мне требуется получить код выхода rsync. По какой-то причине этот код не попадает ни stdout, ни в stderr. В итоге мне пришлось использовать конструкцию:
Именно эта конструкция по какой-то причине не работает асинхронно.
Чтобы код заработал асинхронно, потребовалось создать прослойку в виде bash-скрипта:
#!/bin/bash
rsync -avz -e "ssh -p $2 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" [email protected]$1:$4 $5 >> $6 2>&1
echo $? >> $6
# rsync_download.sh sshHost sshPort sshLogin target destinity logPath
$command = $shDir . "rsync_download.sh $sshHost $sshPort $sshLogin $directory $snapshotPath $logPath > /dev/null 2>&1 &";
exec($command);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question