为什么subprocess.Popen参数长度限制小于操作系统报告的限制?

Rei*_*eid 11 python linux subprocess command-line-arguments python-3.x

我在Linux 3.16.0上运行Python 3.4.3.我想subprocess.Popen用一个长单个参数(一个复杂的Bash调用)运行一个命令,大约200KiB.

根据getconfxargs,这应该在我的范围内:

$ getconf ARG_MAX
2097152
$ xargs --show-limits < /dev/null
Your environment variables take up 3364 bytes
POSIX upper limit on argument length (this system): 2091740
POSIX smallest allowable upper limit on argument length (all systems): 4096
Maximum length of command we could actually use: 2088376
Size of command buffer we are actually using: 131072
Run Code Online (Sandbox Code Playgroud)

但是,Python以极小的限制失败:

>>> subprocess.Popen('echo %s > /dev/null' % ('a' * (131072-4096)), shell=True, executable='/bin/bash')
<subprocess.Popen object at 0x7f4613b58410>
>>> subprocess.Popen('echo %s > /dev/null' % ('a' * (262144-4096)), shell=True, executable='/bin/bash')
Traceback (most recent call last):
  [...]
OSError: [Errno 7] Argument list too long
Run Code Online (Sandbox Code Playgroud)

请注意,Python限制与"实际使用"命令缓冲区xargs报告大致相同.这表明xargs在某种程度上足够聪明,可以从较小的限制开始并根据需要增加它,但Python不是.

问题:

  1. 为什么Python限制小于OS限制2MiB?
  2. 我可以增加Python限制吗?
  3. 如果是这样,怎么样?

Pad*_*ham 13

单个字符串参数的最大大小限制为131072.它与python无关:

~$ /bin/echo "$(printf "%*s" 131071 "a")">/dev/null
~$ /bin/echo "$(printf "%*s" 131072 "a")">/dev/null
bash: /bin/echo: Argument list too long
Run Code Online (Sandbox Code Playgroud)

它实际上MAX_ARG_STRLEN是决定单个字符串的最大大小:

作为自2.6.23以来的附加限制,一个参数不得长于MAX_ARG_STRLEN(131072).如果您生成一个长期调用,例如"使用长参数'生成的sh -c',这可能会变得相关".(Xan Lopez和Ralf Wildenhues指出)

的讨论ARG_MAX,"参数数目和一个参数的最大长度",并在这个问题unix.stackexchange.

你可以在binfmts.h:

/*
 * These are the maximum length and maximum number of strings passed to the
 * execve() system call.  MAX_ARG_STRLEN is essentially random but serves to
 * prevent the kernel from being unduly impacted by misaddressed pointers.
 * MAX_ARG_STRINGS is chosen to fit in a signed 32-bit integer.
 */
#define MAX_ARG_STRLEN (PAGE_SIZE * 32)
#define MAX_ARG_STRINGS 0x7FFFFFFF

~$ echo $(( $(getconf PAGE_SIZE)*32 )) 
131072
Run Code Online (Sandbox Code Playgroud)

您可以传递多个长度的字符串131071:

subprocess.check_call(['echo', "a"*131071,"b"*131071], executable='/bin/bash',stdout=open("/dev/null","w"))
Run Code Online (Sandbox Code Playgroud)

但是单个字符串arg不能超过131071个字节.