Running continuous commands linux using java runtime Exec

I need to run two linux commands using java code, as follows:

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();
        }

The problem is that the output of the second command ("whoamI") does not show the current user used on the first command ("Su – test")!! Is there any problem with this code?

Solution

Such as Javadoc for runtime Exec ():

Every time a command is executed through exec (), it will be executed in a separate child process This also means that Su immediately stops the presence effect on return, which is why the whoamI command will be executed in another child process, using the user who originally started the program again

su test -c whoami

Will give you the results you want

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>