bash 分叉两个进程并在第一个完成后杀死第二个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2694588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:00:23  来源:igfitidea点击:

Fork two processes and kill the second when the first is done

bashkill

提问by User1

I want to create a bash script that will launch two processes and kill the second process when the first is done. Here's an example:

我想创建一个 bash 脚本,该脚本将启动两个进程并在第一个进程完成后终止第二个进程。下面是一个例子:

#fork first process
producer&

#fork second process
consumer&

#wait for producer to finish
...

#kill the consumer
...

I have a feeling this can get ugly but has a very simple solution. Please help me fill in the blanks.

我有一种感觉,这可能会变得丑陋,但有一个非常简单的解决方案。请帮我填空。

回答by ndim

foo & pid_foo=$!
bar & pid_bar=$!

wait $pid_foo
kill $pid_bar

But perhaps you could just run foo | bar(if that happens to work with stdin/stdout handling).

但也许您可以直接运行foo | bar(如果这恰好适用于 stdin/stdout 处理)。

回答by frankc

#!/bin/bash 

#enable job control in script
set -m

producer &

consumer &

fg %1

kill %2