【问题标题】:Kill background process on SIGINT在 SIGINT 上杀死后台进程
【发布时间】:2017-06-15 00:47:15
【问题描述】:

我有这个脚本,它应该在 Bash for Windows 下启动一个 keep-alive 脚本和 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 下运行带有 GUI 的 Sublime Text 3 和 Xorg 服务器。我尝试使用"C:\Windows\System32\bash.exe" -c "./my-script.sh" 命令创建一个快捷方式来启动此脚本,并且当我使用ST3 时,Windows 的Bash 必须在后台运行,否则会出现dbus 错误(即使您修改了/etc/dbus-1/session.conf

问题是:如果我按CTRL+Ctail进程仍然在后台呈现。

编辑:

我更改了脚本中的顺序,将tailwait 放在了所有内容的下方。

已解决:

看起来dash 不支持SIGINTINT。解决方案是使用bashSIGINT 将正常工作。

【问题讨论】:

  • 您的wait 命令会导致脚本暂停并等待所有后台作业完成。所以你的tail 命令必须在sublime 命令启动之前完成。这是你的意图吗?至于tail的问题,或许你可以试试sleep的持续时间很长?
  • 不,tail 命令证明 Bash for Windows,也就是 Win10 的 Linux 子系统应该在后台与 ST3 并行运行,因为 dbus 问题。如果你关闭 ST3,这不会影响这个脚本,至少这不是我最初打算做的。
  • 看起来dash 不支持SIGINTINT。解决方案是使用bashSIGINT 即可。

标签: linux bash shell sh dash-shell


【解决方案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"

【讨论】:

  • 这真的很有趣。是否可以在不显示 sublime 的情况下做类似的事情(例如在 CI 环境中)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 2015-01-11
相关资源
最近更新 更多