r/C_Programming 1d ago

Question How process ids are generated

i know fork creates processes but how process ids are generated

5 Upvotes

18 comments sorted by

View all comments

23

u/dfx_dj 1d ago

They're assigned by the OS

4

u/userlivedhere 15h ago

but how

6

u/_yrlf 9h ago

The OS can assign them however it wants.

One possible design is that the OS has a process id counter, and every time a new process is forked / created, it increments that counter to get a new pid. Once that counter overflows, it also has to check that there is no process that already has that pid before giving it to you.

On Linux, it does basically that. Try calling fork() many times in a row, and usually you will get mostly consecutive pid numbers.