Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 4244896
Votes 104
Synopsis (process) Provide System.getPid(), System.killProcess(String pid)
Category java:classes_lang
Reported Against 1.3 , 1.2.1 , 1.2.2 , mantis-beta
Release Fixed
State 6-Fix Understood, request for enhancement
Priority: 3-Medium
Related Bugs 4073195 , 4199068 , 4250622 , 6457899 , 6751342
Submit Date 08-JUN-1999
Description


Hi,

RFE: Needs getPid(), getEnvVar(), killProcess(String pid) From the java.lang.System class 

1. getPid() => shuld able to give the process id of the jvm process 
it is running in (java.exe)

2. getEnvVar() => shuld able to return either Windows/Unix Environment 
Variable
[for this, please see bug 4199068]

3. killProcess(String pid) => shuld kill the process given the pid
if the process has permissions to do so

This  functions are important and avialable in the two most popular 
os's windows and unix. In case if a particular os does not have support
for this two calls you can return UnSupportedMethodExcetion.

In our server development lot of times we needed these functions
we wrote a jni C wrapper to get this values which will make the code
not 100% pure java code

Please let me know if you need any further info 

Thanks,
Rama Krishna
rama_krishna@ customer .com
(Review ID: 84103) 
======================================================================




A DESCRIPTION OF THE REQUEST :
There are some ways for checking for a running application's instance (creating lock file, creating a listening socket, RMI invocation) but they are all unnecessary unsecure (socket, RMI) or typically unsafe (lock file -- since you can remove it under Unices).
Since Windows'es are supporting PIDs/mutexes, there is a uniform possibility to check for single instance -- create a PID file. Unfortunately, there is no way to get PID for running Java app from Java itself.

JUSTIFICATION :
It would be a great improvement to integrate a getPID() method. It can be also useful for some other purposes.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Something like this:
(int) java.lang.System.getPID();
(Review ID: 187540)
======================================================================
Posted Date : 2006-01-06 20:03:47.0
Work Around



Create native code using JNI for each platform being used, very difficult
solution.
(Review ID: 107079)
======================================================================
An easier solution than JNI is to use an external program, e.g.
perl -e 'print getppid()'
and capture the output of that.
Evaluation
We now appreciate the pragmatic need for much of this functionality even though it is inherently platform specific.

  xxxxx@xxxxx   2003-01-10

Environment variable support is being implemented as a separate RFE.
I am removing the request for getEnvVar() from the synopsis for this RFE.
It currently looks unlikely we will address support for PIDs in Tiger,
so I am de-committing this bug for Tiger.
  xxxxx@xxxxx   2003-08-11
Posted Date : 2006-01-10 02:49:48.0

A minimal and safe design to ease the life of folks writing script-like code in Java,
I suggest:

/** Returns a string identifying the current process. */
String System.getpid();

/** Returns a string identifying the subprocess. */
String Process.getpid();

The intent is that the returned Strings can be used in operating system
commands (like Unix "kill") that operate on processes.
Posted Date : 2008-01-25 02:11:28.0
Comments
  
  Include a link with my name & email   

Submitted On 13-AUG-1999
asharif
Hi, 
I have encountered a need to the the process id 
and have to write JNI calls too. 
It would really be nice if this request could be
accomodated
Thanks
Aziz Sharif


Submitted On 18-AUG-1999
27295
Any kind soul want to post the jni code to get the pid?


Submitted On 11-APR-2000
dkf
See also BugID: 4250622


Submitted On 11-JUL-2000
cow_woc
Furthermore, there needs to be a way to kill a subprocess along with all the children
it spawned... Killing the subprocess alone is not enough in the case where we run:
"xterm -e myProgram" .. XTERM would be killed but myProgram would continue running,
which is not what we want..


Submitted On 26-JAN-2002
dbraat
particulary the getId on process... this would be very 
useful for logging and taking action based upon logs.


Submitted On 16-MAY-2002
shankar.unni
The main reason for providing system-level functionality 
like this is that real-life Java applications often have 
to deal with messy system interfaces. Making everyone 
compile their own native interfaces for every possible 
platform is counter-productive. A well-tested and secure 
implementation by Sun would greatly enhance the usefulness 
of Java as a systems programming language.

I do understand your points, in regard to things like 
process ID (may not be just one, or may not even have 
one). Ditto with environment, etc.

However, this does not preclude you from creating an API 
where you document that this is information that is only 
available when the host system provides it. 

Understand that for most of us, 100.00% portability is not 
an issue, because no ISV will ever guaratee to support a 
java program on every possible platform - most of us only 
support our programs on those environments where we have 
personally tested them ("Write once, test everywhere" :-/).

In 99.999% of the cases, the commonly used host systems 
(Unix, Linux, Windows, Mac, VMS, etc.) all have roughly 
analogous concepts to these functions. And in many cases, 
we *need* to access these things from Java.

(In the specific case of the "many PIDs", there is always 
a root PID, which is the PID when you enter main(); In the 
case of environments, you use whatever your main sees in 
envp[] in main()).

Being 99% portable on 99% of the platforms is much more 
useful than being 100% portable but severely restricting 
the functionality to only the guaranteed common 
environment.


Submitted On 04-JUL-2002
grlea
>There is no guarantee that JVMs and OS processes are in 
one-to-one correspondence.

What's the point? Make that clear in the documentation and 
people know the limits of it. This is not a reason not to 
implement it, just a constraint on the implementation.

getPID() would be very beneficial on both 
java.lang.Runtime, for the current JVM, and 
java.lang.Process, to find the PID of child processes.

Some examples of why this is needed:

- I know you can destroy() a Process in Java, but if your 
app is not interactive, there's no way to initiate the 
call. If the JVM has started many child processes that all 
have a similar or identical command line, it's almost 
impossible to figure out which one to kill from whatever OS 
you may be using.

- What if I want to set the priority a process started by 
my JVM? I can't do it through the API. Same as previous 
example, I need the PID to easily find the process in my OS.

>>getEnvVar() 

Don't do this. It's so not needed. There's so many other 
ways to get around it: System.getProperty(), Properties 
files, the Preferences API.

>>killProcess(String pid)

Hmmm..... don't know about this one. How often would a JVM 
need to kill a process that it didn't start? And think of 
the security problems it could introduce. I really don't 
want that functionality in my J2SE.

>And why is pid a String?

Probably in case some OS uses strings instead of numbers 
for its PIDs. A number can be represented in a String, but 
not vice versa, so String PIDs would allow for both cases.


Submitted On 08-AUG-2002
k151810
SetPid() would be nice additional feature. This is necessary 
for detaching current process as daemon in Unix. On other 
platforms it could be no-op call (i.e. it shloud be called 
Runtime.detach() ?)


Submitted On 05-JAN-2003
shankar.unni
Regarding environment variables:

1. System.getProperty() is *NOT* an adequate substitute.
Don't forget that in most cases, java programs have to
coexist with other programs that often use environment
variables to communicate with each other. Recoding the
entire surrounding environment is hardly an option. 

One possible solution that is tempting to consider is to
define a set of predefined properties that reflect the
environment (java.env.<envvar>, for each environment
variable. But this is bad, because System.getProperty(), by
definition, is case-sensitive, while getenv() can be
case-sensitive or case-insensitive depending on the
platform. A dedicated separate call (System.getenv()) is
more suitable.

2. The distinction mentioned above about "system" and "user"
environment variables is a red herring. The distinction is
only for the system itself; *programs* never see a "system"
vs a "user" environment variable on Windows. You call
getenv(), and the call returns a user environment variable
if one is defined with that name, else it returns a system
environment variable if there is one of that name.

In this regard, the application model for getenv() is
identical on Windows, Unix, Linux and MacOS X. What have we
covered here? About 99.999% of all existing platforms?

3. This also closely ties in to other enhancement requests
(e.g. bug 4109888) - for instance, there needs to be a way
to get the entire environment in a single call (either as an
array, or an iterator), so that one can *augment* the
environment being passed to a child process via
Runtime.exec(). This is again very important when java
programs coexist with other programs in a system.


Submitted On 09-JAN-2003
DaveLaw
Hi,
in my humble opinion getPid() is an absolute MUST HAVE.
As Java conquers the world, my PC is gonna be full of
java.exe processes & I want to cancel the right one!
As far as I can see, all Java platforms have a pid which
should be int & not String.
IMPORTANT
=========
Logically, I believe getPid() belongs in Thread & Process
but NOT in System.  Also I am NOT convinced that
killProcess() is necessary: to kill a Thread or Process from
within the JVM, the destroy() Method should be used & from
outside, the corresponding OS command is used anyway.
WORKAROUND
==========
Use xFunction (www.excelsior-usa.com).  This is a generic
JNI Interface for Windows & Unix.  The code for Windows
would then look like this:
Integer pid = (Integer)new xFunction("msvcrt","int _getpid
()").invoke();

Regards, David Law.  (sorry about the SHOUTING !)

P.S. have the 22 Votes in 4250622 been counted here?


Submitted On 09-JAN-2003
DaveLaw
David.Law@apconsult.de


Submitted On 06-FEB-2003
chistoph_waitz
Hi,
I have the same problems killing processes and using 
environment variables. 
1) I start a process that starts a process that starts ....
All processes are used in synchronous way. I have to add a 
timeout.
How can I get rid off all of them if the timeout occurs? 
Unfortunately I only can destroy() the first process and child 
processes keep alive (Windows NT). => Please help!
2) Anyone of my child processes need a special env variable. 
When I set this single env variable, all others are gone. So I 
had to write a *platform dependend method* to read all the 
env vars and add the necessary to them. Then I can pass 
them to exec().


Submitted On 21-APR-2003
castalia
There is a very simple solution to obtaining the PID for
those Java environments that utilize UNIXProcess to
implement the abstract Process class. This involves
trivial modifications to the Java source for Process.java
and UNIXProcess.java (these files are available from the
src.zip archive file of the JSDK distribution). No JNI
mods or additions are needed.

Add the following abstract method to the end of the Process
class definition in Process.java:

	/**
	 * Gets the Process ID that uniquely identifies the system
process.
	 *
	 * @return	the integer ID used by the system to identify
the process.
 	 */
	abstract public int ID();

Then add the implementation of this method to the end of
the UNIXProcess class definition in UNIXProcess.java:

	public int getID() {
	return pid;
	}

Note that the UNIXProcess class already contains the PID,
but it's private and has no accessor method. Also note that
the specific source code in UNIXProcess.java varies from
platform to platform (I've found that the Linux version is
different from the Solaris and Darwin versions), but that
doesn't matter because they all contain the pid variable
(they have to, of course, to uniquely identify the process
on the system, duh, to waitFor or destroy it). So the same
trivial accessor method will work.

Compile these java files to class files. Put the class files
in a java/lang subdirectory. Update your rt.jar file (this
will be called classes.jar on Darwin) in your JRE lib
directory (this may be /usr/java/jre/lib for Solaris, or
/System/Library/Frameworks/JavaVM.framework/Versions/<v#>Classes
for Darwin). I assume you've remembered to make a
backup of the jar file you are going to update and that
you have write permission for it. So, for example:

jar uf /usr/java/jre/lib/rt.jar java

This will use the Process.class and UNIXProcess*.class (4 or
5) files in your java/lang subdirectory to replace the same
files in the jar archive.

NOTE: This does not in any way modifiy any existing
functionality of your JRE, it just adds an accessor method
for the pid value that was hidden there all along.

It would, of course, be preferable if the addition of getID
to the Process class definition was incorporated in a
consistent and ubiquitous manner by the Java developers.

I have tested this successfully for Solaris, Linux, and
Darwin (Apple OS-X). I would be interested to hear if this
solution, in whatever particular form it takes, works in
MS-OS environments.


Submitted On 12-AUG-2003
_grlea_
Why has accessing environment variables - a problem with
many simple, platform-independent workarounds (e.g. use
properties files!) - been perceived as more important than
providing process control?

Surely this can't be too hard to incorporate. Are we going
to have to wait another two years for the next major release
before we see it?


Submitted On 26-FEB-2004
washu123
The JDK, distributed by sun actually is littered with 
calls to getpid (unix) and getHandle under windows, it 
would be trivial for sun to add a getPid function to 
Runtime and process classes.


Submitted On 05-MAR-2004
Rarb@GB
Come on Sun, this started 4.5 years ago. Give us the 
PID. We need it. We want it. We demand it.
And another thing ... you will save a lot of developers a 
lot of time currently spent searching through the 
documentation trying to find a getPID method that isn't 
there! I just wasted a couple of hours trying to find 
something useful to get me the PID of my current Java 
process - before I made it to here. This kind of thing 
upsets the very developers who are most using your 
product.
Rarb.


Submitted On 20-MAY-2005
bumphrey
with jdk 1.5 you can try something like this:
   protected static String PID; 
   static {
      RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean();      
      PID = rtb.getName();
      System.setProperty(


Submitted On 15-NOV-2005
vpertsov
A simple way to retrieve the process id on unix:

Process p = Runtime.getRuntime().exec("test.ksh");
Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
System.out.println( f.get( p ) );

This, of course, assumes that your security policy allows you to do this. 


Submitted On 15-NOV-2005
vpertsov
One more thing, you can then execute the ptree command, parse the output, and kill all the process ids. 


Submitted On 08-AUG-2006
Loadmaster
We're up to Java 1.6, and I looks like getPID is still not there.

By the way, System.getPID() should return a String instead of an int, in order to support the widest number of platforms (including those that give processes actual names instead of numbers).


Submitted On 08-JUN-2007
We are in 2007, and still no getPid method ...
I still don't get why such a useful method doesn't exist.


Submitted On 16-AUG-2007
I agree that there should be a way to get the currently running Processes ID (PID).

In my case I am trying to track mutliple instances of an application running in a common log file. I am using log4j but it does not support this feature (because Java doesn't support it). log4perl does provide the exact functionality I want.

I am fairly new to Java and have been impressed with it, but every so often I run into these idiosyncracies that make no sense to me.  I am especially confused as to why it is taking SUN 8 years to implement this obviously popular feature.  And people think Microsoft doesn't listen to developers.


Submitted On 06-SEP-2007
java.lang.management.RuntimeMXBean has a getName() method, which in its current implementation returns the jvm process PID.

I talked on the java open source forums about fixing this. There is a Sun engineer assigned to this bug, but it is not as easy as you might think... 

Some JVMs are clustered (many in one OS, or many over many OSes), what should they return? The JVM is ported to limited hardware devices that don't even have processes, what should they return? Most current OSes have an int as process id... but some may have characters in there, and future OSes might have long rather than int as pid..... None of these are insurmountable problems of course, but require lots of work for all JVM implementors (Sun are not the only ones), which explains why it might take time to implement this right.



Submitted On 02-NOV-2007
SWPalmer
"There is a Sun engineer assigned to this bug, but it is not as easy as you might think... 

Some JVMs are clustered (many in one OS, or many over many OSes), what should they return?"

Irrelevant.  When launching a process from Java there should be a way to get the PID of that process via the Process class.  Clustered VMs are outside of the scope of what is needed here.


Submitted On 20-NOV-2007
Come on guys.. 8 years on and what would be a very useful method is still not available.


Submitted On 20-NOV-2007
Another vote for "Go away ! Leave it be !" 
and "fuggedaboudit !"

If this were truly a useful item, it would have been finished eight years ago.


Submitted On 16-FEB-2008
Mr_Light
Hello, a couple of things.
Process.getPid(); -> Process.getId(); (Process id, Process.getProcessID, getPid, its ambigious.)
System.getpid() -> System.getProcessId(); (here, it might well be unclear at first glance. no need to save characters.)

I disagree with the listed intent, it's intent should be, as mentioned above, to allow for logging messages so one can track and debug processes. by changing the intent as such you can drop the need for it to be correct(non-null) at all times(not filled in from the start) in those 0,1% cases where it frustrates the implementation.

For kill well I disagree with the implementation of destroy() at this time. distroy by no mean sounds like a nice way to terminate a process and gives the impression that it would be permanently disposed of. Allowing it to be gracefully shutdown or even reject the shutting down signal is and should not be the intent of destroy it's a clean up method.

for actual interaction with the process to allow it to shutdown or change the flow completely(cancel shutdown? frontend process?) should be handled in new (RFE) methods alike 
boolean getShutdownVote(); (true->agreed, false->disagreed, null->unsupported)
int shutdown() or int shutdownGracefully()
(int-> exitcode as with waitfor() I do wonder to what extend ExitCode is actually os-independed?)

The RFE can be implemented in a OS-independed matter. 


Submitted On 10-APR-2008
rbygrave
System.getPid() would also be useful in using the attach API - Ala attach to the current VM to... add agents etc.


Submitted On 22-MAY-2008
desd1012
See also issue 6698619 for a simple Thread API to return the task id.
Under linux, this is under /proc/(jvmpid)/tasks/(threadid)


Submitted On 22-OCT-2008
rednoah42
These methods should have been in the api since the beginning ...


Submitted On 21-NOV-2008
GooglyMoogly
It would also be extremely useful if we could get a handle on a process (to create a process object), if we knew the process identifier.

This isn't for the purpose of running script-like code in Java. This is so we can keep the code in java and not have to resort to another language for process handling. It's difficult seeing how this is inherently platform specific when all platforms have some sort of process identifier and basic process handling should be built in to any serious programing language.


Submitted On 10-DEC-2008
Here is the solution for get the PID from a process for windows and unix, perhaps this helps until Sun provides the getPID().
http://golesny.de/wiki/code:javahowtogetpid



PLEASE NOTE: JDK6 is formerly known as Project Mustang