Bash脚本:无法正确处理SIGTSTP [英] Bash script: can not properly handle SIGTSTP

查看:87
本文介绍了Bash脚本:无法正确处理SIGTSTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,可以挂载和卸载设备,该脚本在这之间执行一些读取操作.由于设备非常慢,脚本需要大约15秒才能完成(挂载至少需要5-6秒).由于将此设备挂载会导致其他问题,所以我不希望此脚本被中断.

I have a bash script that mounts and unmounts a device, which performing some read operations in between. Since the device is very slow, the script takes about 15 seconds to complete (the mount taking atleast 5-6 seconds). Since leaving this device mounted can cause other problems, I don't want this script to be interrupted.

话虽如此,我可以正确处理SIGINT(Ctrl + c),但是当我尝试处理SIGTSTP(Ctrl + z)时,脚本将冻结.这意味着信号被捕获,但处理程序无法运行.

Having said that, I can correctly handle SIGINT (Ctrl+c), but when I try to handle SIGTSTP (Ctrl+z), the script freezes. Which means the signal is trapped but the handler doesn't run.

#!/bin/sh
cleanup()
{
    # Don't worry about unmounting yet. Just checking if trap works.
    echo "Quitting..." > /dev/tty
    exit 0
}
trap 'cleanup' SIGTSTP
...

我必须手动将KILL信号发送到该进程.知道为什么会发生这种情况以及如何解决吗?

I manually have to send the KILL signal to the process. Any idea why this is happening and how I can fix it?

推荐答案

在当前执行中的进程终止之前,shell不会执行陷阱. (至少,这是bash 3.00.15的行为).如果通过^ c发送SIGINT,则会将其发送到前台进程组中的所有进程;否则,它将被发送到前台进程组.如果当前正在执行的程序收到该消息并终止,则bash可以执行该陷阱.与SIGTSTP类似,通过^ z; bash接收到信号,但是直到正在运行的程序终止后才执行陷阱,如果采用默认行为并将其挂起,则bash不会执行该操作.尝试用简单的read f替换...,并注意陷阱会立即执行.

The shell does not execute the trap until the currently executing process terminates. (at least, that is the behavior of bash 3.00.15). If you send SIGINT via ^c, it is sent to all processes in the foreground process group; if the program currently executing receives it and terminates then bash can execute the trap. Similarly with SIGTSTP via ^z; bash receives the signal but does not execute the trap until the program that was being run terminates, which it does not do if it takes the default behavior and is suspended. Try replacing ... with a simple read f and note that the trap executes immediately.

这篇关于Bash脚本:无法正确处理SIGTSTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆