英文:
How can I store a subshell PID in a variable so that I can kill the subshell and its background process later?
问题
所以,假设我正在运行一个带有后台进程的子shell,如下所示:
```bash
(command &)
我希望能够将此子进程的PID存储到一个bash变量中,以便稍后可以杀死子shell和其运行的后台进程。我该如何做?
注意:这很可能是一个重复的问题,但我在实施许多其他答案时遇到了困难。因此,即使将此问题标记为重复,我仍然会感激如果有人能够提供答案。
我尝试过的一些方法:
pid="$((echo "$BASHPID" && command &))"
pid2="$((command & echo "$BASHPID"))"
pid3=(echo "$BASHPID" && command &)
pid4=(command & echo "$BASHPID")
<details>
<summary>英文:</summary>
So, let us say I am running a subshell with a background process as follows:
```bash
(command &)
I want to be able to store the PID of this subprocess into a bash variable so that I can kill the subshell and its running background process later. How can I do so?
Note: This may very well be a duplicate, but I am struggling to implement many of the other answers. So, even if this question is marked as a duplicate, I would appreciate it if someone could still provide an answer regardless.
Some things I have tried:
pid="$((echo "$BASHPID" && command &))"
pid2="$((command & echo "$BASHPID"))"
pid3=(echo "$BASHPID" && command &)
pid4=(command & echo "$BASHPID")
答案1
得分: 2
一个想法:
$ read -r x < <(sleep 240 & echo $!) # 替代方法:用 $BASHPID 替换 $!
^^^^^^^^^ ^^
$ echo "$x"
1887
^^^^
$ ps -aef|egrep sleep
myuser 1887 1 pty1 16:00:17 /usr/bin/sleep
^^^^ ^^^^^
$ pgrep -a sleep
1887 sleep 240
^^^^ ^^^^^^^^^
英文:
One idea:
$ read -r x < <(sleep 240 & echo $!) # alternative: replace $! with $BASHPID
^^^^^^^^^ ^^
$ echo "$x"
1887
^^^^
$ ps -aef|egrep sleep
myuser 1887 1 pty1 16:00:17 /usr/bin/sleep
^^^^ ^^^^^
$ pgrep -a sleep
1887 sleep 240
^^^^ ^^^^^^^^^
答案2
得分: 1
有许多方式进行进程间通信。例如,可以使用一个命名管道:
pidfile=$(mktemp -n)
mkfifo "$pidfile"
(command & echo $! > "$pidfile")
read pid < "$pidfile"
rm "$pidfile"
英文:
There are many ways of https://en.wikipedia.org/wiki/Inter-process_communication . For example use a fifo:
pidfile=$(mktemp -n)
mkfifo "$pidfile"
(command & echo $! > "$pidfile")
read pid < "$pidfile"
rm "$pidfile"
答案3
得分: 0
或许实现它的最简单方式是使用 coproc
:
#! /bin/bash
coproc ./mycommand
pid=$COPROC_PID
英文:
Perhaps the shortest way of achieving it is using coproc
:
#! /bin/bash
coproc ./mycommand
pid=$COPROC_PID
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论