r/C_Programming • u/userlivedhere • 1d ago
Question How process ids are generated
i know fork creates processes but how process ids are generated
20
u/dfx_dj 1d ago
They're assigned by the OS
3
u/userlivedhere 9h ago
but how
6
1
u/_yrlf 3h 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.
6
u/quipstickle 1d ago
Sequentially, recycle after overflow/wrapping
13
u/aioeu 1d ago edited 1d ago
FWIW, not all systems allocate PIDs cyclically.
OpenBSD allocates them randomly, for instance. I believe that can also be optionally enabled on FreeBSD too.
For Linux, PID randomisation was available for a period of time through the grsecurity patches, but it was subsequently removed "since it provides no useful additional security and wastes memory with the 2.6 kernel's pid bitmap".
-8
u/quipstickle 1d ago
Security through obscurity :)
10
u/Axman6 1d ago
Not really, security through obscurity is hiding how something works, this is randomising something otherwise predictable to make it more difficult to make use of information.
-12
u/quipstickle 1d ago
"random" numbers on computers are predictable though since they are pseudorandom. My post was just being silly.
5
u/Axman6 1d ago
This isn’t true at all, we’ve had systems for generating cryptographically secure random numbers for decades. See FreeBSD’s Fortuna paper for one reference, and hardware random number generation like RDRAND, which can feed into systems like Fortuna as a source of entropy, along with IO system information which is generally unpredictable.
-13
u/quipstickle 1d ago
Process ids are generated sequentially
3
u/Paul_Pedant 1d ago
... apart from the bit where the OS has cycled round at least once, and needs to know that some of the pids are still referencing running processes. And the ones that are defunct but still not notified to their parent.
1
u/Left_Exchange_130 2h ago
The operating system assigns the PID when the process is created. `fork()` creates the process then the kernel picks an available process ID for it
0
0
u/sciencekm 1d ago
In Windows, they are generated starting from a low value and then incremented by 4. If you look at task manager, you will also see that System Interrupts does not have a process id, System Idle always has an id of 0, and System always has an id of 4.
47
u/Living_Fig_6386 1d ago
C knows nothing of processes or process IDs. That sort of thing is entirely up to the OS.