Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 如何终止管道后台进程?_Linux_Bash_Pipe - Fatal编程技术网

Linux 如何终止管道后台进程?

Linux 如何终止管道后台进程?,linux,bash,pipe,Linux,Bash,Pipe,示例会话: - cat myscript.sh #!/bin/bash tail -f example.log | grep "foobar" & echo "code goes here" # here is were I want tail and grep to die echo "more code here" - ./myscript.sh - ps PID TTY TIME CMD 15707 pts/8 00:00:00 bash 2070

示例会话:

- cat myscript.sh 
#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
# here is were I want tail and grep to die
echo "more code here"

- ./myscript.sh

- ps
  PID TTY          TIME CMD
15707 pts/8    00:00:00 bash
20700 pts/8    00:00:00 tail
20701 pts/8    00:00:00 grep
21307 pts/8    00:00:00 ps
正如你所看到的,tail和grep仍然在运行


像下面这样的东西会很棒

#!/bin/bash
tail -f example.log | grep "foobar" &
PID=$!
echo "code goes here"
kill $PID
echo "more code here"

但是这只会杀死grep,而不会杀死tail。

尽管整个管道在后台执行,但只有
grep
进程的PID存储在
$中。您想让
kill
终止整个作业。您可以使用
%1
,这将终止当前shell启动的第一个作业

#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
kill %1
echo "more code here"


即使您只是杀死
grep
进程,
tail
进程也应该在下次尝试写入标准输出时退出,因为当
grep
退出时,该文件句柄已关闭。根据example.log的更新频率,这可能是立即的,也可能需要一段时间。

您可以在脚本末尾添加
kill%1


这将首先杀死创建的
后台,这样就不需要找出PID等。

kill-9$PID
也许?@AndersR.Bystrup,它仍然只杀死
grep
,但信号不同。
kill%1
将杀死创建的第一个作业,而不是最后一个作业(虽然在本例中,只有一个后台作业,因此第一个和最后一个作业是相同的)。
kill%%
kill%%
将终止当前作业(即最近创建的作业)工作。这显然是有效的,但有人知道它在哪里吗?我希望能读到更多关于这方面的内容,但在
mankill
或其他任何我通过网络搜索找到的地方都没有。