How to get child process from parent process

前端 未结 9 579
清歌不尽
清歌不尽 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:11

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

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

    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/

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

    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,...
    
    0 讨论(0)
  • 2020-11-30 23:20

    Just use :

    pgrep -P $your_process1_pid
    
    0 讨论(0)
  • 2020-11-30 23:21

    I'v written a scrpit to get all child process pids of a parent process. Here is the code.Hope it helps.

    function getcpid() {
        cpids=`pgrep -P $1|xargs`
    #    echo "cpids=$cpids"
        for cpid in $cpids;
        do
            echo "$cpid"
            getcpid $cpid
        done
    }
    
    getcpid $1
    
    0 讨论(0)
  • 2020-11-30 23:23
    #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;
    

    }

    0 讨论(0)
提交回复
热议问题