以这个脚本为例,仅作为示例
#!/bin/sh
foo ()
{
eval "$@"
}
touch bar
foo tail -f bar &
sleep 1
kill $!
在此示例中,我想 kill tail,但是因为tail作为 an 的结果被调用eval,所以它不会被杀死。我怎么能tail不使用 , 等来pgrep杀人pkill?
改为使用exec应该可以
#!/bin/sh
foo ()
{
exec "$@"
}
touch bar
foo tail -f bar &
sleep 1
kill $!
如果与管道一起使用,则需要进行进程替换
foo tail -f bar > >(tee baz) &
这是因为,当 you 时kill $!,它实际上是子shell(foo &),它会被SIGTERM. 你不是在杀死tail命令。
正如 svnpenn 所提到的,要么使用exec,以便 subshell 的 PID 由tail.
或使用以下代码进行树遍历:
kill `ps -C tail --ppid $! -opid=`
它将列出所有-C tailpid 为 $! 的尾进程 () ( --ppid $!) & 只打印它的 PID-opid=然后杀死那个 pid。