在SIGINT上杀死后台进程

时间:2017-01-29 21:23:37

标签: linux bash shell sh dash-shell

我有这个脚本,它应该在Bash for Windows下启动一个保持活动的脚本和Sublime Text 3:

#!/bin/dash

set -e

# Keep alive (in background)
tail -f /dev/null &
pid=$!

echo "tail process id: ${pid}"
echo "Keep-alive process started with Sublime Text 3\nPress SIGINT (CTRL+C) to kill it..."

# Start Sublime Text 3
DISPLAY=localhost:0 /usr/bin/sublime

# http://stackoverflow.com/a/19274804/1442219
trap "kill ${pid}; exit 1" INT
wait

此代码生成:

tail process id: 49
Keep-alive process started with Sublime Text 3
Press SIGINT (CTRL+C) to kill it...
tail: cannot determine location of '/dev/null'. reverting to polling: Invalid argument

这个脚本的全部目的是我在Bash for Windows下使用带有Xorg服务器的GUI运行Sublime Text 3。我尝试使用"C:\Windows\System32\bash.exe" -c "./my-script.sh"命令创建一个快捷方式来启动此脚本,当我使用ST3时,Bash for Windows必须在后台运行,否则会出现dbus错误(即使您修改了{{1} }})

问题是:如果我按/etc/dbus-1/session.confCTRL+C进程仍会在后台显示。

修改

我更改了脚本中的排序,将tailtail置于一切之下。

解决:

看起来wait不支持dashSIGINT。解决方案是使用INTbash将按预期工作。

1 个答案:

答案 0 :(得分:1)

看起来dash不支持SIGINTINT(至少在Windows的Linux子系统中就是这种情况)。解决方案是使用bashSIGINT将按预期工作。

sublime.sh:

#!/bin/bash

set -e

# Just to make sure, this line takes PID1 in Docker environments
# So SIGINT/SIGKILL won't be blocked
echo "pid1" > /dev/null

echo -e "\n///////////////////////////////////////////////\n"

# Keep alive (in background) hack from Docker environments
tail -f /dev/null &
pid[0]=$!

echo "tail process id: ${pid[0]}"
echo -e "Keep-alive process started with Sublime Text 3\nPress SIGINT (CTRL+C) to kill it..."

# Start Sublime Text 3
DISPLAY=localhost:0 /usr/bin/sublime

# http://stackoverflow.com/a/19274804/1442219
# http://stackoverflow.com/a/360275/1442219
trap "kill ${pid[0]}; exit 1" SIGINT

echo -e "\n///////////////////////////////////////////////\n"

wait

sublime.cmd

@ECHO OFF
"C:\Windows\System32\bash.exe" -c "./sublime.sh"