Kill background process on SIGINT

一笑奈何 提交于 2020-01-17 05:49:41

问题


I have this script, which should start a keep-alive script and Sublime Text 3 under Bash for Windows:

#!/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

This code generates:

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

The whole purpose of this script that I run Sublime Text 3 with GUI with Xorg server under Bash for Windows. I try to make a shortcut to start this script with "C:\Windows\System32\bash.exe" -c "./my-script.sh" command and Bash for Windows have to run in the background when I use ST3, because otherwise there are dbus errors (even if you modified /etc/dbus-1/session.conf)

The problem is: If I press CTRL+C, tail process is still presented in the background.

Edit:

I changed the ordering in the script, putted tail and wait under everything.

Solved:

Looks like dash isn't supporting SIGINT or INT. Solution is to use bash and SIGINT will work as it should.


回答1:


Looks like dash isn't supporting SIGINT or INT (at least this is the case in the Linux subsystem for Windows). Solution is to use bash and SIGINT will work as it should.

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"


来源:https://stackoverflow.com/questions/41926123/kill-background-process-on-sigint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!