How to get child process from parent process

前端 未结 9 580
清歌不尽
清歌不尽 2020-11-30 23:05

Is it possible to get the child process id from parent process id in shell script?

I have a file to execute using shell script, which leads to a new process

相关标签:
9条回答
  • 2020-11-30 23:25

    The shell process is $$ since it is a special parameter

    On Linux, the proc(5) filesystem gives a lot of information about processes. Perhaps pgrep(1) (which accesses /proc) might help too.

    So try cat /proc/$$/status to get the status of the shell process.

    Hence, its parent process id could be retrieved with e.g.

      parpid=$(awk '/PPid:/{print $2}' /proc/$$/status)
    

    Then use $parpid in your script to refer to the parent process pid (the parent of the shell).

    But I don't think you need it!

    Read some Bash Guide (or with caution advanced bash scripting guide, which has mistakes) and advanced linux programming.

    Notice that some server daemon processes (wich usually need to be unique) are explicitly writing their pid into /var/run, e.g. the  sshd server daemon is writing its pid into the textual file /var/run/sshd.pid). You may want to add such a feature into your own server-like programs (coded in C, C++, Ocaml, Go, Rust or some other compiled language).

    0 讨论(0)
  • 2020-11-30 23:27

    I am not sure if I understand you correctly, does this help?

    ps --ppid <pid of the parent>
    
    0 讨论(0)
  • 2020-11-30 23:31
    ps -axf | grep parent_pid 
    

    Above command prints respective processes generated from parent_pid, hope it helps. +++++++++++++++++++++++++++++++++++++++++++

    root@root:~/chk_prgrm/lp#
    
     parent...18685
    
     child... 18686
    
    
    root@root:~/chk_prgrm/lp# ps axf | grep frk
    
     18685 pts/45   R      0:11  |       \_ ./frk
    
     18686 pts/45   R      0:11  |       |   \_ ./frk
    
     18688 pts/45   S+     0:00  |       \_ grep frk
    
    0 讨论(0)
提交回复
热议问题