C Tutorial: Playing with processes

Getting a process' process ID (PID)

Every process on the system has a unique process ID number, known as the pid. This is simply an integer. You can get the pid for a process via the getpid system call.

Example

This is a small program that simply prints its process ID number and exits.

/* getpid: print a process' process ID */ /* Paul Krzyzanowski */ #include <stdlib.h> /* needed to define exit() */ #include <unistd.h> /* needed to define getpid() */ #include <stdio.h> /* needed for printf() */ int main(int argc, char **argv) { printf("my process ID is %d\n", getpid()); exit(0); }

Download this file

Save this file by control-clicking or right clicking the download link and then saving it as getpid.c.

Compile this program via:

gcc -o getpid getpid.c

If you don't have gcc, You may need to substitute the gcc command with cc or another name of your compiler.

Run the program:

./getpid

Recommended

The Practice of Programming

 

The C Programming Language

 

The UNIX Programming Environment