使用java runtime exec运行连续的Commands Linux [英] Run consecutive Commands Linux with java runtime exec

查看:62
本文介绍了使用java runtime exec运行连续的Commands Linux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用以下Java代码在Linux上运行两个命令:

I need to run two commands Linux using java code like this:

 Runtime rt = Runtime.getRuntime();
          
           
            Process  pr=rt.exec("su - test");
            String line=null;
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
          
            while((line=input.readLine()) != null) {
                
                System.out.println(line);
            }
           pr = rt.exec("whoami");
             input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

             line=null;

            while((line=input.readLine()) != null) {
                 System.out.println(line);
            }               
            int exitVal = pr.waitFor();
            System.out.println("Exited with error code "+exitVal);              
        } catch(Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }

问题是第二个命令("whoami")的输出不显示在第一个命令("su-test")上使用的当前用户!这段代码有什么问题吗?

The problem is the output of the second command ("whoami") doesn't display the current user which used on the first command ("su - test")! Is there any problem on this code please?

推荐答案

在单独的进程中执行指定的字符串命令.

每次通过exec()执行命令时,它将在单独的子进程中执行.这也意味着su的影响一经返回便立即消失,这就是为什么 whoami 命令将在另一个子进程中执行的原因,再次使用最初启动该程序的用户.

each time you execute a command via exec() it will be executed in a separate subprocess. This also means that the effect of su ceases to exist immediately upon return, and that's why the whoami command will be executed in another subprocess, again using the user that initially launched the program.

su test -c whoami

将为您提供所需的结果.

will give you the result you want.

这篇关于使用java runtime exec运行连续的Commands Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆