

Linux 的进程 pid 编号极限
source link: https://xie.infoq.cn/article/1d9382ccd70f27c19c7d49e20
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

整理本文,起源是看到知乎上的一个问题, 为什么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/
Recommend
-
14
用来检测异常活动的最有用的技术之一是对父子进程关系的分析,然而,技术更高明更强大的攻击者可以使用父PID(PPID)欺骗来绕过此操作,从而允许从任意父进程执行恶意进程。尽管这项技术本身并不新鲜,虽然
-
16
随想录(串级PID的学习)
-
12
Intro to Control Theory Part Two: PID tuning control
-
10
Intro to Control Theory Part 1: PID control
-
15
linux如何根据进程pid获取路径 发表于 2018-07-31 20:07:47...
-
15
Reading /proc/pid/cmdline can hang forever Back in August, I wrote that fork() can fail and it made a pretty big splash. Continuing with that general theme, I'll tell you...
-
9
Linux PID 1 和 Systemd Linux PID 1 和 Systemd 要说清 Systemd,得先从Linux操作系统的启动说起。Linux 操作系统的启动首先从 BIOS 开始,然后由 Boot Loader 载入内核,并初始化内核。内核初始化的最后一步就是启动 init...
-
5
Linux namespace in Go - Part 1, UTS and PIDThis article starts some Golang experiments on Linux namespace and provides context for Container technology. Linux namespace is an im...
-
5
容器通过 Linux Namespace 技术,对网络、PID、用户等等信息的隔离。 从进程的角度来说,你可以在 Host 上看到所有容器内的进程。 或者更准确的说,当你在 Ho...
-
10
【笔记】Linux 上查看 USB 设备的 PID 和 VID 捕捉一只爱折腾的绯鞠 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK