How to get the process id of a bash subprocess on command line

后端 未结 6 1308
庸人自扰
庸人自扰 2020-12-15 03:47

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

(list) list  is  executed  in  a  subs         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 04:02

    Unfortunately there's no easy way to do this prior to bash version 4, when $BASHPID was introduced. One thing you can do is to write a tiny program that prints its parent PID:

    int main()
    {
        printf("%d\n", getppid());
        return 0;
    }
    

    If you compile that as ppid and put it in your path, you can call it, eg:

    $ (echo $$; ppid)
    2139
    29519
    $ (x=$(ppid); echo $x)
    29521
    

    One oddness I noticed, however, is that if you write

    $ (ppid)
    

    it doesn't seem to actually run it in a subshell -- you need at least two commands inside the parentheses for bash to actually run them in a subshell.

提交回复
热议问题