r/C_Programming • • Sep 01 '26

Question How process ids are generated

i know fork creates processes but how process ids are generated

6 Upvotes

22 comments sorted by

View all comments

27

u/dfx_dj Sep 01 '26

They're assigned by the OS

5

u/userlivedhere Sep 02 '26

but how

12

u/Mortomes Sep 02 '26

That is up to the OS to decide.

6

u/_yrlf Sep 02 '26

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.

3

u/Key_River7180 Sep 03 '26

The os keeps track of the highest process ID assigned, when you make a process It just gets you the highest id + 1 and increases the counter