How to get the running process’ parent process’ ID in C / C++?

Posted on In QA

How to get the running process’ parent process’ ID in C / C++?

In C and C++, you can call the getppid() library function which is a function from the POSIX library.

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

pid_t getppid(void);   

getppid() returns the process ID of the parent of the calling process.

Example usage:

getppid.c

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

int main()
{
  pid_t ppid = getppid();

  printf("ppid: %lun", ppid);
}

Build and run it:

$ gcc getppid.c -o s && ./s
ppid: 22312

Verify the pid of the parent process (the Bash shell):

$ echo $$
22312

Leave a Reply

Your email address will not be published. Required fields are marked *