如何获得一个bash子进程的命令行上的进程id [英] How to get the process id of a bash subprocess on command line

查看:1226
本文介绍了如何获得一个bash子进程的命令行上的进程id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在bash中,我们可以创建一个使用圆括号子shell 。按照bash的手册页:

I know in bash we can create subshells using round parenthesis ( and ). As per bash man page:

(list) list  is  executed  in  a  subshell environment 

另外要获得当前进程ID :我们使用:

echo $$

现在我的问题是如何得到一个子shell的进程ID创建使用在命令行?

Now my question is how to get process id of a subshell created using ( and ) on command line?

如果我用这个:

echo $$; ( echo $$; ) 

我会在父shell的进程两次印刷,因为 ID在stdout $ 获取创建子shell甚至在扩大。因此,如何真正迫使懒惰的扩张?

I will get the parent shell's process id printed twice on stdout since $$ gets expanded even before subshell is created. So how to really force the lazy expansion?

[解决方案应在Mac上工作,以及不只是Linux的]

建议的链接回答没有,因为工作回声$ BASHPID 不起作用在我的Mac和返回空白。

Suggested linked answer doesn't work since echo $BASHPID does not work on my Mac and returns blank.

推荐答案

感谢大家对您花费宝贵的时间在这里找到回答我的问题。

Thanks to all of you for spending your valuable time in finding answer to my question here.

不过我现在回答我的问题,因为我已经找到了一个的破解的方式得到的bash该PID版本< 4(将在所有版本的工作,虽然)。下面是命令:

However I am now answering my own question since I've found a hack way to get this pid on bash ver < 4 (will work on all the versions though). Here is the command:

echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; )

它打印:

5642
13715

在哪里13715是子shell的pid。为了测试这个时候我做的:

Where 13715 is the pid of the subshell. To test this when I do:

echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; bash $F; ps; )

我得到这样的:

5642
13773
  PID   TT  STAT      TIME COMMAND
 5642 s001  S      0:02.07 -bash
13773 s001  S+     0:00.00 -bash

告诉我,13773确实是子shell的PID。

Telling me that 13773 is indeed the pid of the subshell.

注意:我又回到了我原来的解决方案,因为作为@ChrisDodd评论说,回声$$; (bash的-c'回声$ PPID')不起作用的Linux。上述煤矿的解决方案,在Mac和Linux两种工作

Note: I reverted back to my original solution since as @ChrisDodd commented that echo $$; ( bash -c 'echo $PPID'; ) doesn't work Linux. Above solution of mine works both on Mac and Linux.

这篇关于如何获得一个bash子进程的命令行上的进程id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆