linux ulimit与java无法正常工作

我在linux ubuntu 17.10上运行代码

public class TestExec { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "ulimit", "-n"}); BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } 

此代码返回“无限”

但每当我从终端运行命令时,我得到1024。

为什么这些数字不同?

如果从命令行运行相同的命令,则会得到相同的结果:

 $ "/bin/sh" "-c" "ulimit" "-n" unlimited 

这是因为-c只查看紧随其后的参数,即ulimit-n不是此参数的一部分,而是指定为位置参数( $0 )。

要运行ulimit -n-n需要成为该参数的一部分:

 $ "/bin/sh" "-c" "ulimit -n" 1024 

换句话说,你应该使用:

 new String[]{"/bin/sh", "-c", "ulimit -n"}