如何立即跳过循环并进入陷阱kill命令进行处理? [BASH]

时间:2017-11-11 13:16:35

标签: bash

我的剧本:

For R = 6 to lastrow

SQLQuery2 = "SELECT * FROM Mfg.databasemodels_note where typeId = " & Sheets("Sheet1").Range("B" & R) & " AND date < " & Sheets("Sheet1").Range("I" & R) & " order by date asc limit 1;"

当我向运行我脚本的进程发送命令#!/bin/bash finish() { echo "[$(date -u)] I was terminated." exit } trap finish SIGINT SIGTERM echo "pid is $$" while true do echo 'I am running' sleep 15 done 时,我必须等到执行kill -SIGTERM <pid>。我用谷歌搜索但没有找到任何答案如何立即突破循环并在发送sleep 15命令时执行trap

1 个答案:

答案 0 :(得分:5)

这个问题或多或少得到了回答:Linux: How to kill Sleep。简而言之,执行脚本的bash shell获取kill信号,但sleep调用没有。

如果您希望进程处于休眠状态,则可以在后台执行sleep,同时对其执行wait。这样,父进程将获得您的信号并可以自由处理它。在您的代码中:

#!/bin/bash
finish() {
    echo "[$(date -u)] I was terminated."
    exit
}
trap finish SIGINT SIGTERM
echo "pid is $$"
while true
do
    echo 'I am running'
    sleep 15 &
    wait
done

请记住,您的kill信号将被父进程捕获,该进程将立即终止,但sleep 15仍将在后台运行,直到完成为止。您可以通过添加kill $!来终止此休眠过程,该bash会终止wait执行的上一个后台进程。

最后一句话。 <?php $con = mysqli_connect(mydatabase_address, myid, password); $userLocation = $_POST["userLocation"]; $stmt = mysqli_prepare($con, "SELECT * FROM neighborTable WHERE postLocation = ?"); mysqli_stmt_bind_param($stmt, "s", $userLocation); mysqli_execute($stmt); mysqli_stmt_bind_result($stmt, $ID, $postWriter, $postContent, $postDate, $postPic, $postLike, $postComments, $postLocation, $profilePic, $postGatherDate, $postGatherLocation, $postGatherTime); $response = array(); while($row = mysqli_stmt_fetch($stmt)) { $row_array['ID'] = $ID; $row_array['postWriter'] = $postWriter; $row_array['postContent'] = $postContent; $row_array['postDate'] = $postDate; $row_array['postPic'] = $postPic; $row_array['postLike'] = $postLike; $row_array['postComments'] = $postComments; $row_array['postLocation'] = $postLocation; $row_array['profilePic'] = $profilePic; $row_array['postGatherDate'] = $postGatherDate; $row_array['postGatherLocation'] = $postGatherLocation; $row_array['postGatherTime'] = $postGatherTime; array_push($response, $row_array); } echo json_encode(array("response"=>$response), JSON_UNESCAPED_UNICODE); mysqli_close($con); 可能会等待一个或多个进程完成。没有参数,它将等待所有子进程完成。如果指定了进程,它还将返回完成的最后一个进程的状态。如果不是(如示例中所示),则返回0.