[linux] How to get child process from parent process

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 process1 (parent process). This process1 has forked another process process2(child process). Using script, I'm able to get the pid of process1 using the command:

cat /path/of/file/to/be/executed

but i'm unable to fetch the pid of the child process.

This question is related to linux shell process child-process

The answer is


To get the child process and thread, pstree -p PID. It also show the hierarchical tree


For the case when the process tree of interest has more than 2 levels (e.g. Chromium spawns 4-level deep process tree), pgrep isn't of much use. As others have mentioned above, procfs files contain all the information about processes and one just needs to read them. I built a CLI tool called Procpath which does exactly this. It reads all /proc/N/stat files, represents the contents as a JSON tree and expose it to JSONPath queries.

To get all descendant process' comma-separated PIDs of a non-root process (for the root it's ..stat.pid) it's:

$ procpath query -d, "..children[?(@.stat.pid == 24243)]..pid"
24243,24259,24284,24289,24260,24262,24333,24337,24439,24570,24592,24606,...

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

ps --ppid <pid of the parent>

You can get the pids of all child processes of a given parent process <pid> by reading the /proc/<pid>/task/<tid>/children entry.

This file contain the pids of first level child processes.

For more information head over to https://lwn.net/Articles/475688/


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

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).


I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.

function getcpid() {
    cpids=`pgrep -P $1|xargs`
#    echo "cpids=$cpids"
    for cpid in $cpids;
    do
        echo "$cpid"
        getcpid $cpid
    done
}

getcpid $1

#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    // Create a child process     
    int pid = fork();

    if (pid > 0)
    {

            int j=getpid();

            printf("in parent process %d\n",j);
    }
    // Note that pid is 0 in child process
    // and negative if fork() fails
    else if (pid == 0)
    {





            int i=getppid();
            printf("Before sleep %d\n",i);

            sleep(5);
            int k=getppid();

            printf("in child process %d\n",k);
    }

    return 0;

}


Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to process

Fork() function in C How to kill a nodejs process in Linux? Xcode process launch failed: Security Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes Linux Script to check if process is running and act on the result CreateProcess error=2, The system cannot find the file specified How to make parent wait for all child processes to finish? How to use [DllImport("")] in C#? Visual Studio "Could not copy" .... during build How to terminate process from Python using pid?

Examples related to child-process

Use child_process.execSync but keep output in console How do I debug "Error: spawn ENOENT" on node.js? How to get child process from parent process