写点什么

Linux 的进程 pid 编号极限

发布于: 2021 年 01 月 05 日
Linux的进程pid编号极限

整理本文,起源是看到知乎上的一个问题,为什么Linux的进程pid编号极限最大值( process pid max)是131070?


问题中提到,通过提问者的测试(Ubuntu18.04 操作系统下),Python 脚本实现的分配进行 pid 脚本,渠道系统自动分配给进程的最大 pid 值是 131070,这是一个并不特殊的值。(通常可以想到的上限会是与二进制数字相关,例如 1024,65536 等等)。


很高兴,看到还是有很多人在坚持知乎的本来精神,先问是不是,再问为什么。  


Linux 内核的进程 PID 最大值并非 131070,而是 32768 (32 位系统)和 2 的 22 次方(64 位系统)。这是 Linux 手册中明确给出的说明:


/proc/sys/kernel/pid_max (since Linux 2.5.34)

This file specifies the value at which PIDs wrap around (i.e., the value in this file is one greater than the maximum PID). PIDs greater than this value are not allocated; thus, the value in this file also acts as a system-wide limit on the total number of processes and threads. The default value for this file, 32768, results in the same range of PIDs as on earlier kernels. On 32-bit platforms, 32768 is the maximum value for pid_max. On 64-bit systems, pid_max can be set to any value up to 2^22 (PID_MAX_LIMIT, approximately 4 million).


为了方便理解,上述内容翻译成中文:


/proc/sys/kernel/pid_max (从 Linux 2.5.34 版本开始)


这个文件明确指定了 pid 的取值范围(也就是说,文件中的值是允许的最大 pid 值+1)。比这个数字大的值将不会分配为 pid。因此,此文件中的值还作为系统范围内进程和线程总数的限制。此文件的默认值 32768,与早期内核的 PID 范围相同。 在 32 位系统中,32768 是 pid_max 的最大值。64 位系统,pid_max 最大可达 2^22。(PID_MAX_LIMIT,约 4 亿)。


到达极限的情况:


1、当 PID 达到上限后,内核会从 0 重新开始寻找可用的 PID 并分配。


2、而所有 PID 均已被占用的话,则将抛出


fork failed: Resource temporarily unavailable


提问者所说的最大值应该只是发行版设置( CentOS 8.0 64 位上为 400w 左右)。通过上述 Linux 手册中的说明,我们也可以通过修改/proc/sys/kernel/pid_max 这个文件的值来调整 pid 的取值范围。


在测试环境的机器上查看了这个文件的设置(系统版本:Linux 3.10.0-1127.18.2.el7.x86_64):



可见,虽然是 64 位系统,但默认也设置了 32768,确实如手册中描述一致。通过:


echo value > /proc/sys/kernel/pid_max 


手动修改,可以设置预期的最大 pid 数值(2^22 以下)


附 Linux 内核源码地址:

官网链接:https://www.kernel.org/

git: https://git.kernel.org/

镜像:https://mirrors.edge.kernel.org/pub/


发布于: 2021 年 01 月 05 日阅读数: 1310
用户头像

磨炼中成长,痛苦中前行 2017.10.22 加入

微信公众号【程序员架构进阶】。多年项目实践,架构设计经验。曲折中向前,分享经验和教训

评论

发布
暂无评论
Linux的进程pid编号极限