How to get the running process' pid in C / C++?

How to get the running process' pid in C / C++?

asked Jun 5 by dtivl (2,500 points)

1 Answer

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

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

pid_t getpid(void);

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

Example usage:

getpid.c

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

int main()
{
  pid_t pid = getpid();

  printf("pid: %lu\n", pid);
}

Build and run it:

$ gcc getpid.c -o s && ./s
ppid: 7108
answered Jun 5 by dtivl (2,500 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...