Thread: Question related to getpid and getppid

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    85

    Question related to getpid and getppid

    Good evening,

    i would like to ask you sthg related to finding the parent's id of a process.

    I need my C program to output e.g. 48 : 47 --> - 34 --> - 2 --> - 0

    where 48 is the id of the process,47 is the parent's id,-34 is the parent's id of the parent of the process etc.

    I do :

    Code:
    #include <unistd.h>    
    #include <sys/types.h>  
    #include <errno.h>      
    #include <stdio.h>      
    #include <sys/wait.h>   
    #include <stdlib.h>     
    
    int main() {
    
    printf("The process id is %d\n",getpid());
    printf("The processes parent's id is %d\n",getppid());
     
    }
    What shall i do in order to output the parent's,parent id and the other ids?
    Thanks,in advance!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Use a pipe and when you fork, pass it to the child.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Dec 2006
    Posts
    85
    Well,can't i use some other function like getpid and getppid in order to output the desirable result?

  4. #4
    .
    Join Date
    Nov 2003
    Posts
    307
    Are you trying to trace "parentage" back possibly to init (modern UNIX init has pid=1)?
    Or maybe as far as possible...

    getpid and getppid work only in the context of the current process. You can't run them in your process and get the values for some other process. Sorry if I don't get you requirement.
    quzah's advice works great when you are going down to children and "grand"children.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Parsing the output of the "ps" command is about the only easy way of figuring out what all the process IDs are.

    And how come you're outputting negative PIDs?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed