shell_exec 不会停止,即使添加新的 shell_exec 来阻止另一个

shell_exec won't stop even though add new shell_exec to stop the other one

我有一个 PHP 脚本需要 运行 使用 shell_exec

的 .sh 文件
echo shell_exec('sh /var/www/html/daloradius/start.sh > /dev/null 2>/dev/null &');

我只是将其转储到后台。这是我的 start.sh

sudo tcpdump port 1812 -w testing.pcap

我们知道 tcpdump 总是一直在监听,我试图通过触发另一个 shell_exec 的按钮来解决这个问题(停止 tcpdump 进程),即 stop.sh

pid=$(ps aux | grep "sudo tcpdump" | head -1 | cut -d '.' -f 1 | cut -d ' ' -f 7)
sudo kill $pid

Stop.sh 在 cli 中测试时运行良好,但是当我单击触发 start.sh 的按钮并尝试使用触发 stop.sh 的按钮停止它时不起作用。 tcpdump 不会停止,但是当我尝试使用 stop.sh 在 cli 中停止它时,它运行良好。任何人都可以给我解决方案来强制停止 tcpdump 事情吗?谢谢

您尝试使用 bash,而您本应从 php 开始编排流程。

在这里,我们从PHP中获取命令的PID并杀死它。用您拥有的任何代码替换睡眠语句。

<?php
# Script must be run with sudo to start tcpdump
# Be security conscious when running ANY code here
$pcap_file = 'testing.pcap';
$filter = 'port 1812'
$command = "tcpdump $filter -w $pcap_file" . ' > /dev/null 2>&1 & echo $!;';

$pid = (int)shell_exec($command);
echo "[INFO] $pid tcpdump: Writing to $pcap_file\n";

# Some important code. Using sleep as a stand-in.
shell_exec("sleep 5");

echo "[INFO] $pid tcpdump: Ending capture\n";
shell_exec("kill -9 $pid");

请注意,tcpdump 有 -c 选项来停止接收 n 个数据包,您可以使用 -G 旋转文件。您可能需要阅读 tcpdump's manpage 以充分利用它。