About the pid of the process

拟墨画扇 提交于 2019-11-28 13:13:33

This is determined by the Operating System.

In general, they are usually sequentially assigned by the OS. However, this behavior is not something to base decisions upon, since most operating system specifications state that the process ID allocation is not deterministic (ie: it could be random, and could change in a future version, etc).

On Linux, pids are generally allocated sequentially on a system-wide basis, but they will wrap around periodically, and there may be 'gaps' caused by other unrelated processes. In an extreme case, you might have a 'gap' wide enough to cause this wrap-around. So don't assume any particular ordering - instead explicitly keep track of your parent or child process' PIDs.

Here's how to test what your system does:

for i in $(seq 20); do ps; done | grep ps

The PIDs of the "ps" commands are consecutive processes, or as close to consecutive as any other caller could reasonably expect to be able to spawn.

My cygwin terminal on Windows allocates them randomly-ish, my web host allocates them sequentially (with occasional gaps which presumably are for processes run by other users or servers).

Some consider sequential PID allocation to be a slight possible security concern, since it may leak information between users of a multi-user system.

On AIX, you will often see bigger (e.g. 7-digit) PIDs and they are not necessarily allocated semi-sequentially (though I seemed to be cycling in increments of 2 when I tested; there was another user on the machine, so it may not mean much).

Fresh login on an AIX 5.3 machine:

$ ps
     PID    TTY  TIME CMD
 1060910 pts/27  0:00 -ksh
 1155224 pts/27  0:00 ps
$

Depends on your platform, but you shouldn't be dependent on any specific order to your pid's.

On Windows, pid's are usually allocated in increasing numbers, but as processes exit the pid's can be recycled and you will see cases where a newer process has a lower pid than an older process. Also, pid's come out of the same namespace as tid's, so you won't see pid's increasing by 4 as you launch new processes.

From your perspective they will be random. The system manages those numbers and assigns them as processes are created. A quick look at the PID's currently on my system shows that they are all divisible by 4...

If you're creating those childs you'll know the pid, the pid depends on the OS scheduler, you don't care about this stuff.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!