Examining other running Java processes

I've written a process which I want to keep running in the background. I'd like to write an application that I can run which will determine if my first process is already started, and if not to start it. I'd like to be able to use API methods to examine the state of my machine to determine what processes are available (similar to the way a debugger can find a list of running processes) rather than coordinating this through a file on disk. What classes should I examine to be able to do this?

Look at the JMX classes; you can run JConsole to see that it finds running Java processes and lets you connect to them.

Similar Messages

  • Running Java process in Back ground

    We have a script that starts a Java process in Background. But still if I try to exit from the 'Console', it's not allowing me to do so, and if I forcibly kill the console, it's killing my Java process. My question is, how can I make my java process to run completely in background? Secondly, will the JVM have any references to the console through which it is being called. Please help me.

    Hi Sastry66,
    If your application is going to use stdout/stderr, then there may be a problem. Try to redirect stdout/stderr using shell redirections when starting your java program. You may also want to try using exec java <class-file> to start the process.
    Regards,
    SUN/DTS

  • Running java process in a while loop using Runtime.exec() hangs on solaris

    I'm writting a multithreaded application in which I'll be starting multiple instances of "AppStartThread" class (given below). If I start only one instance of "AppStartThread", it is working fine. But if I start more than one instance of "AppStartThread", one of the threads hangs after some time (occasionaly). But other threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside another thread?. Here I'm executing the process in a while loop.
    2. Other thing i noticed is the Thread is hanging after completing the process ("java ExecuteProcess"). But the P.waitFor() is not coming out.
    3. Is it bcoz of the same problem as given in Bug ID : 4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. "
    I'm running this on sun Solaris/java 1.2.2 standard edition. If any of you have experienced the same problem please help me out.
    Will the same problem can happen on java 1.2.2 enterprise edition.?
    class AppStartThread implements Runnable
    public void run()
    while(true)
    try
    Process P=Runtime.getRuntime().exec("java ExecuteProcess");
    P.waitFor();
    System.out.println("after executing application.");
    P.destroy();
    P = null;
    System.gc();
    catch(java.io.IOException io)
    System.out.println("Could not execute application - IOException " + io);
    catch(java.lang.InterruptedException ip)
    System.out.println("Could not execute application - InterruptedException" + ip);
    catch (Exception e)
    System.out.println("Could not execute application -" + e.getMessage());

    I'm writting a multithreaded application in which I'll
    be starting multiple instances of "AppStartThread"
    class (given below). If I start only one instance of
    "AppStartThread", it is working fine. But if I start
    more than one instance of "AppStartThread", one of the
    threads hangs after some time (occasionaly). But other
    threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside
    another thread?. Here I'm executing the process in a
    while loop.Of course this is OK, as your code is always being run by one thread or another. And no, it doesn't depend on which thread is starting threads.
    2. Other thing i noticed is the Thread is hanging
    after completing the process ("java ExecuteProcess").
    But the P.waitFor() is not coming out.This is a vital clue. Is the process started by the Runtime.exec() actually completing or does the ps command still show that it is running?
    3. Is it bcoz of the same problem as given in Bug ID :
    4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited
    ed buffer size for standard input and output streams,
    failure to promptly write the input stream or read the
    output stream of the subprocess may cause the
    subprocess to block, and even deadlock. "These two are really the same thing (4098442 is not really a bug due to the reasons explained in the doc). If the program that you are exec'ing produces very much output, it is possible that the buffers to stdout and stderr are filling preventing your program from continuing. On Windows platforms, this buffer size is quite small (hundreds of characters) while (if I recall) on Solaris it is somewhat larger. However, I have seent his behavior causing problem on Solaris 8 in my own systems.
    I once hit this problem when I was 'sure' that I was emitting no output due to an exception being thrown that I wasn't even aware of - the stack trace was more than enough to fill the output buffer and cause the deadlock.
    You have several options. One, you could replace the System.out and System.err with PrintStream's backed up by (ie. on top of) BufferedOutputStream's that have large buffers (multi-K) that in turn are backed up by the original out and err PrintStream's. You would use System.setErr() and System.setOut() very early (static initializer block) in the startup of your class. The problem is that you are still at the mercy of code that may call flush() on these streams. I suppose you could implement your own FilterOutputStream to eat any flush requests...
    Another solution if you just don't care about the output is to replace System.out and System.err with PrintStreams that write to /dev/nul. This is really easy and efficient.
    The other tried and true approach is to start two threads in the main process each time you start a process. These will simply consume anything that is emitted through the stdout and stderr pipes. These would die when the streams close (i.e. when the process exits). Not pretty, but it works. I'd be worried about the overhead of two additional threads per external process except that processes have such huge overhead (considering you are starting a JVM) that it just won't matter. And it's not like the CPU is going to get hit much.
    If you do this frequently in your program you might consider using a worker thread pool (see Doug Lea's Executor class) to avoid creating a lot of fairly short-lived threads. But this is probably over-optimizing.
    Chuck

  • All Java Processes crash on RH Linux 7.3 / 6.3 without any comment

    We have the following Problem on two Machines. We installed j2sdk1.4.0 first, then jdk-1.3.1_04 (Because of other Problems with 1.4.0).
    Now all running java Processes crash after up to two hours without any comment, any error file. Looks like they were killed by the 'kill' Command. The running java Processes are different Programs, that do very different things.
    The OS on the two machines are RH Linux 7.3 and 6.3 - normal installation without any essential changes.
    I would be very happy, if someone have an idea, how to solve this Problem. If you need additional Information, ask for.
    Holger

    ... if someone have an idea, how to solve this Problem.Seems like I remember seeing a problem like that.
    It turned out that indeed it was the 'kill' command. Another process was running, looking for the app, and killing it when it found it.
    We spend quite a bit of time trying to figure out why our app was 'crashing' before deciding to look elsewhere (when we discovered the other process.)

  • Get process-ID of particular java process?

    I have created a startup script for air-video-server which happens to be a java application.
    The problem I'm facing now is that I can't identify the process ID of the particular java process using pidof.
    ps aux | grep AirVideo shows:
    user 4180 7.0 0.3 2309364 31288 pts/0 Sl 12:51 0:00 java -jar AirVideoServerLinux.jar
    Here's the line I'm using right now:
    PID=`pidof -o %PPID java`
    but this obviously lists the process IDs of all running java processes, not just air-video-server.
    PID=`pidof -o %PPID ava -jar AirVideoServerLinux.jar`
    doesn't match anything at all.

    pgrep(1) might help you

  • Running a process within a java program

    Hi
    I have code that runs a process for performance monitoring on an installed system. When I run the code standalone as below, it runs fine. If I include the code below inside another java program, the process fails to execute and the status returned is non-zero (failed to execute).
    The process requires the PATH and LD_LIBRARY_PATH to be set which seem to be set correctly when i print them out. So, I am not sure why the process doesnot run when included within another running java program.
    Can someone please point out what I maybe missing?
    Thanks!!
    public class RunPerf
      private static final String CLASS_NAME = "RunPerf"; private static Process proc = null;
    public static void main(String[] args)
        String INSTALLPERF_SAW_UNIX_COMMAND = "sawexe" + " " + "-perf";
             StringBuffer path1 = new StringBuffer(30);StringBuffer ldlibpath1 = new StringBuffer(30);
        System.setProperty("user.home", "/home/user");
        StringBuilder commandToExecute = new StringBuilder();
       commandToExecute.append(System.getProperty("user.home"));
       commandToExecute.append(File.separator);
       commandToExecute.append("web");
       commandToExecute.append(File.separator);
       commandToExecute.append("bin");
       commandToExecute.append(File.separator);
         String path = System.getProperty("user.home")+"/server/bin/" + File.pathSeparator + System.getProperty("user.home")+ "/web/bin";
           path1.append( path );
           path1.append( File.separator );
           path1.append( System.getProperty("java.library.path") );
           path1.append( File.separator );
          String env_value = null;
         String[] ldargs = {"LD_LIBRARY_PATH"};
         for (String env: ldargs) {
                env_value = System.getenv(env);
             System.out.println("LD_LIBRARY_PATH value before setting property= " + env_value);
                if (env_value != null) {
               String newldlibpath = System.getProperty("user.home")+ "/server/bin/" + File.pathSeparator + System.getProperty("user.homee")+ "/web/bin" ;
                ldlibpath1.append(newldlibpath);
                ldlibpath1.append(File.separator);
                   ldlibpath1.append(env_value);
                   ldlibpath1.append( File.separator);
                    System.out.format("%s=%s%n", env,ldlibpath1.toString());
                } else {
                    System.out.format("%s is not assigned.%n", env);
                 commandToExecute.append(INSTALLPERF_SAW_UNIX_COMMAND);
                   String[] envp =   { "USER_HOME =" + "/home/user",          "PATH=" + path1.toString(), "LD_LIBRARY_PATH=" + ldlibpath1.toString() };
               int status = executeCommand1(commandToExecute.toString(), envp,null);
                   if(status != 0){
                          System.out.println("Unable to run perf Unix") ;
         public static int executeCommand1(String command,String[] envp, Logger logger) {
            String METHOD_NAME = "executeCommand1";
            if (logger == null) { logger = Logger.getAnonymousLogger();}
            logger.entering(CLASS_NAME, METHOD_NAME, new Object[] { command, envp});
            Runtime runtime = Runtime.getRuntime();
            runtime.addShutdownHook(new Thread() {
                        public void run() {
                            if (proc != null) {     try {  proc.destroy();  if (proc != null) { proc.destroy();  }
                                } catch (Exception e) {
                                    e.printStackTrace(); }      }      }     });               
                           int retVal = 0;
          File cwd = new File(System.getProperty("user.home")+ "/web/bin/");               
                           try {
                               if (envp != null) {   proc = runtime.exec(command, envp,cwd); }
                                       else {  proc = runtime.exec(command); }
                               Thread t_err =        new Thread(new StreamReader(proc.getErrorStream()));
                               t_err.start();
                               Thread t_in =     new Thread(new StreamReader(proc.getInputStream()));
                               t_in.start();
                               retVal = proc.waitFor(); } catch (IOException e) {        retVal = -1;   logger.severe("IOException");      }
                                     catch (Exception e) { retVal = -1;        logger.severe("Exception");                  }
                     logger.exiting(CLASS_NAME, METHOD_NAME, retVal);
                     return retVal;
    static class StreamReader implements Runnable {
            InputStream in;
            public StreamReader(InputStream genericStream) {   in = genericStream;   }
            public void run() {
                try {
                    String strTemp = null;
                    BufferedReader buffReader = new BufferedReader(new InputStreamReader(in));
                    while ((strTemp = buffReader.readLine()) != null) {
                        System.out.println(strTemp);                }
                } catch (Exception e) {               e.printStackTrace();            }        }    }}

    Either set up a script before the program runs or have the
    program write a script file which contains the statements
    that need to be executed. Then you will be able to
    execute the script with a call to
    Runtime.getRuntime().exec()Mark

  • Ps -p running very slow (1-2 seconds) on Java process

    Hi Solaris gurus:
    I encountered a issue that running ps -p on java process running very slow, it took almost 2 seconds to complete.
    I issued a truss on the "ps -p " command, the following is part of the output:
    /1: 0.0001 fstat(1, 0xFFFFFFFF7FFFE1F0) = 0
    /1: 0.0000 write(1, " U I D P".., 55) = 55
    /1: 0.0002 open("/proc/19299/psinfo", O_RDONLY) = 3
    */1: 1.3170 read(3, "02\0\0\0\0\0\011\0\0 K c".., 416) = 416*
    /1: 1.2401 close(3) = 0
    /1: 0.0002 stat("/dev/tty", 0xFFFFFFFF7FFFE830) = 0
    It seems that the read() spent the most time.
    Anyone can help?

    Not enough memory, page-outs is too large
    8.91 GB    Page-outs
    After removing adware, and do a safe boot of Safari and remove extensions, then reset cache history etc. You need to do a boot into Recovery Mode and run Disk Repair from there. Also boot the system in Safe Mode.
    On startup it sounds like you have a problem with the directory which would also account for long startups and checking the directory. Along with or instead of DU Repair Disk you can use Single User Mode and fsck -fy to try to fix the directory but in some cases that may not be enough.
    Backups from before you got this adware and problems helps and should always be ready and able to restore a system from known good backups or system restore image.
    4GB of RAM may have been fine originally but "Early 2011" is now 5 years and 4 OS version changes. You can upgrade the memory and while at it consider a nice SSD internal drive which will help as well. Take a look and see what prices and options there are from http://www.macsales.com for your 2011 MacBook Pro.
    http://www.everymac.com
    Community for MBP MacBook Pro

  • Run java as a different process name in Linux

    I have multiple java applications running on a linux platform. When I look at the process list, they all say java. I want them to have a unique process name. The closest I have gotten is starting the java app in a script, and that script name shows up as well as the java app. This could be all fine and dandy, but if someone kills the script, the java process continues on. It would be nice if I could say run this process as this name in Linux, but I know of no such thing. I asked this on LinuxQuestions.org and got a response to use Launch4J...which creates executables for Windows...so that wasn't very helpful. I was hoping the Java community might have a little more insight.

    rename the java binaryOr instead of renaming, you could do a symlink... I
    don't have a machine to test on, but I think creating
    a symlink to the java executable and running that
    symlink would change the executable's name in the
    process table.nah, the process would still be called 'java'

  • I want to run java program on windows environment as background process

    Hi all
    I want to run java program on windows environment as background processSo command prompt return after executing java command and program on background In Linux we can do this easily �but I do not how to do this in windows
    for example look this programe
    import java.io.*;
    import java.util.*;
    public class TestClass {
         class ravi extends Thread{
              public void run(){
                   try {    
                        String target_file = "ravind.txt";
                        File targetfile = new File(target_file);
                        PrintWriter writer = new PrintWriter(new FileWriter(targetfile)) ;
                   for (int i =0 ; i < 100 ;i++ ){
                        Thread.sleep(10000);
                        writer.println(" ravindra shukla ");
              } catch (Exception e) {               
                             e.printStackTrace();
         public static void main(String[] args) {
              TestClass test1 = new TestClass();
              TestClass.ravi r1 = test1.new ravi();
              r1.start();          
    System.out.println(" return from main ");
    first i compile this
    javac TestClass.java
    then i run this by using this command
    java TestClass
    but becouse i put sleep on threads run function so it takes to much time to get return on command promt .... i want to run this programe as background process so command promt return as soon as i execute java command

    Thanks dude
    This solution �start java TestClass� works fine �. But it does not solve my problem
    It opens another black window and that black window persist till the life time of my program
    Is it possible application run on complete background without opening another black window �as in Linux

  • Checking running non java process

    Hey,
    i need to write a program that checks if a non-java process is still running (under windows) and to run a system command if it is not. Is there a way to check what process are still running?
    Thanks

    You will have to make use of native methods for that. Or use something with Runtime.exec();

  • J2EE:some java processes running

    HI!
    I have a general question regarding the SAP Solution Manager.
    We have succesfully installed SAP SOLMAN 4.0 (Windows, Oracle).
    Unfortunately when I start SAP system with MMC-Console, I see that the Java-instance is yellow.
    (disp+work.exe --> tells, J2EE:some java processes running).
    I cann log on to the system, but it scares me a lot (in Tr. SICK are no errors).
    <b>Can some one tell, wheter it is critical and how can I solve this problem?</b>
    Thank you!
    regards

    it seems, that your j2ee engine is not coming up correctly.
    Check note 943498  (and also see other relevant notes in Note 724452 - Central Note for SAP NetWeaver Java Server 04/2004s)
    Markus

  • Does different Java processes spawn different JVMs running on a server ?

    Hi,
    I have 2 applications running on AIX server, one is weblogic server and the other one is inhouse developed Java application. I have set the heap sizes for both the applications and when I do
    ps ax | grep JavaI get
    /usr/java14/bin/java -Xms2048m -Xmx2048m (weblogic)
    /usr/java14/jre/bin/java -Xmx320m -Dvert.log.prefix (inhouse Java)I was wondering if these two processes have their own JVM or as they are running on the same server they share the same JVM. I read in some Java related article that even though there are multiple Java processes, they share the same JVM when run on a single server.
    So from the above Java processes is it true that the total Java heap size is 2048+320=2368M and is used by only one JVM?
    I appreciate if anyone who can answer or direct me to some resources which might give me some answers.
    Thanks,
    kraziabtu

    No, you have two totally independent JVM's. As with many O/S's AIX (and I'm so sorry for you on that :) will only load a single copy of things like read only data segments, shared libraries and some other things but the processes are separate.
    Your first process is allowed to grow to a maximum of 2GB and your second one is set at 320 MB. Again, as there are two of them they are not related.
    Need Java help? Want to help people who do? Sit down with a cup of Java at the hotjoe forums.
    Sure they're new - come get them started!

  • How to Set up the  variables and others to compile and Run Java Programs

    Hello,
    I have just downloaded the jdk1.6.0_07 and jre1.6.0_07 and installed it in C:\Program files\Java in my Windows XP ,So please tell me how to sett up the enviroment variables etc to compile and run Java Programs from Command Prompt.
    thanks

    To set the PATH permanently, add the full path of the jdk1.6.0_<version>\bin directory to the PATH variable. Typically this full path looks something like C:\Program Files\Java\jdk1.6.0_<version>\bin. Set the PATH as follows on Microsoft Windows:
    1. Click Start > Control Panel > System on Windows XP or Start > Settings > Control Panel > System on Windows 2000.
    2. Click Advanced > Environment Variables.
    3. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:
    C:\Program Files\Java\jdk1.6.0_<version>\bin

  • How can i run Java class form  other java application.

    Hi ,
    I have problem to run java class from my java application,
    I am using the class ClassLoader in order to launched the Java class , it�s work fine whenever, the class exist in the same folder , however , when i am trying to run class that is not in the current folder ,
    i got error (see below),
    Do you have any idea what is wrong?
    java.lang.ClassNotFoundException
         at SimpleClassLoader.loadClass(SimpleClassLoader.java:110)
         at SimpleClassLoader.loadClass(SimpleClassLoader.java:53)
         at Run.main(Run.java:31)

    What does "run an class" mean? You don't run classes. They're not executables.
    I bet your problem is the classpath. You are aware that the classloader looks only there? Unless it's an UrlClassLoader.

  • Create a terminal through my own Java process

    I am cross posting this thread: [http://forums.sun.com/thread.jspa?messageID=10913756|http://forums.sun.com/thread.jspa?messageID=10913756].
    I believe that this will have to be accomplished using a Solaris or UNIX specific device.
    The question is how I can call a process and tell it that it is running in a terminal.
    For example "prstat -a" will adjust to fit the size of the window as well as respond to my keystrokes.
    If I call it using a java process it will not do either of those two things because it detects that it it not in a terminal.
    Is there a process or middleman I can call to create a terminal? Or do I have to write my own middleman in C/C++? (I would really prefer a middleman that is already part of Solaris)

    Darren_Dunham wrote:
    Well, you're asking this in a general OS forum. You might want to ask this in a Java forum.Already did :)
    In general, the process will have to allocate a psuedo-terminal (pty) and use that to talk to the process (so that it sees a terminal is being used). I don't really know how to do that in java.I don't think it is possible without a middleman. Still looking
    I have no idea if it's useful, but this page says it's an implementation of Expect in java. Any implementation is either going to have to open ptys directly, or it's going to have to re-implement their functionality. You might be able to examine the code and see it's accomplishing that.
    [http://expectj.sourceforge.net/]
    That code uses the standard exec function. It does not actually create a terminal (although it still uses a shell). It is similar to running "sh | cat" on your own terminal.
    I will search on psuedo-terminal (pty) later today
    alan.pae wrote:
    http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/prstat/prstat.c
    http://src.opensolaris.org/source/search?q=prstat&defs=&refs=&path=&hist=&project=%2Fonnv
    prstat was an example. I am not looking for a C method to detect a terminal as much as one to create a terminal. If there is something I am missing, please elaborate

Maybe you are looking for

  • Hello. I have a problem with my MacBook Pro. Freezing/Heating up. I am confused.

    I have had my laptop for 2 years now, my problem is that my laptop heats up very quickly and it freezes. It does not only freeze because of the heat.. it sometimes freezes as soon as i open it, even if it has been shut down all night long..I was told

  • FI Account modification from MM via T030

    Hy Expert, I need help about integration from MM to FI when I make a stock variation. My question is where Sap store the account modification when creating an Fi document via stock modification in MM? I explaine: I make an MM Logistic movement on the

  • Don't fall for scams!

    This is a IN-DEPTH guide on how to spot the nonesense that scammers try to tell you. LEGEND SCAM: "A fraudulent scheme performed by a dishonest individual, group, or company in an attempt obtain money or something else of value. Scams traditionally r

  • System crashes on clicking bc- bsp- sap node in SICF

    Hi all    I was trying to change the logon settings for a BSP application. when i clicked the bc->bsp->sap node in the transaction SICF, the system crashed with a exeception a popup window displays [Sapfewdbg Exception Exception #1 has occured and du

  • JBO-25009

    I have a JSF page in which I have an af:inputDate binded to a view object <af:inputDate value="#{bindings.DatImmat.inputValue}" label="#{bindings.DatImmat.hints.label}" required="#{bindings.DatImmat.hints.mandatory}" shortDesc="#{bindings.DatImmat.hi