Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using java to get the current process owner

Tags:

java

unix

I want to know the owner of current process in Unix using Java. I want to find the current server's owner name. I tried with running "who am i" command in Runtime.getRuntime().exec(), but its not returning me any results.

String line = ""; 
Process p = Runtime.getRuntime().exec("who am i");
InputStream iStream = p.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(iStream);
BufferedReader bufReader = new BufferedReader(inputStreamReader);
while ((line = bufReader.readLine()) != null) {
    System.out.println("Input "+line);
}

Is there anything wrong with this code or any idea how can I find the owner of current process using Java?

like image 216
Lolly Avatar asked Oct 31 '12 14:10

Lolly


People also ask

How can one get current process ID in Java?

getRuntimeMXBean(). getPid() method to get the process ID. This method returns the process ID representing the running Java virtual machine.

How can I get the process ID of Java application in Linux?

Fig: 'ps' command displaying all Java processes running on Linux machine. The red color highlight in the above figure indicates the process IDs of all Java processes running on this EC2 instance. From here, you can get hold of your application's process ID.


1 Answers

First thing, I think System.getProperty("user.name") should work for that

Second thing, the reason your code is not returning anything is because the command is whoami with NO SPACES so your exec line should be (assuming you are running on windows through cygwin or on a **nix based system)

Process p = Runtime.getRuntime().exec("whoami");
like image 67
Matthew Kirkley Avatar answered Nov 02 '22 16:11

Matthew Kirkley