How can I store a subshell PID in a variable so that I can kill the subshell and its background process later?

huangapple go评论63阅读模式
英文:

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 &amp;)

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=&quot;$((echo &quot;$BASHPID&quot; &amp;&amp; command &amp;))&quot;
pid2=&quot;$((command &amp; echo &quot;$BASHPID&quot;))&quot;
pid3=(echo &quot;$BASHPID&quot; &amp;&amp; command &amp;)
pid4=(command &amp; echo &quot;$BASHPID&quot;)

答案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 &lt; &lt;(sleep 240 &amp; echo $!)       # alternative: replace $! with $BASHPID
                ^^^^^^^^^        ^^    
$ echo &quot;$x&quot;
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 &quot;$pidfile&quot;
(command &amp; echo $! &gt; &quot;$pidfile&quot;)
read pid &lt; &quot;$pidfile&quot;
rm &quot;$pidfile&quot;

答案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

huangapple
  • 本文由 发表于 2023年2月27日 05:53:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定