Getting the running process own pid in C / C++

Posted on In Programming, QA

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

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.

An example C program to get self process ID getpid.c:

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

int main()
  pid_t pid = getpid();

  printf("pid: %lun", pid);

Build and run it:

$ gcc getpid.c -o s && ./s
pid: 7108

One comment

  1. Please update the reuslt section with actual result.

    $ gcc getpid.c -o s && ./s
    ppid: 7108

    But printf is
    printf(“pid: %lun”, pid);

    How come it prints “ppid” for print statement of “pid”.

Leave a Reply

Your email address will not be published.