Java check if exe is running

Java, Checking if any process ID is currently running on Windows

That post explains how to get all PIDs running on a Windows machine: you’d have to compare the output of the cmd call with your PID, instead of printing it.

If you’re on Unix-like systems you’d have to use with ps instead of cmd

Calling system commands from your java code is not a very portable solution; then again, the implementation of processes varies among operating systems.

Solution 2

How to check if a pid is running on Windows with Java:

Windows tasklist command:

The DOS command tasklist shows some output on what processes are running:

C:\Documents and Settings\eric>tasklist Image Name PID Session Name Session# Mem Usage ========================= ====== ================ ======== ============ System Idle Process 0 Console 0 28 K System 4 Console 0 244 K smss.exe 856 Console 0 436 K csrss.exe 908 Console 0 6,556 K winlogon.exe 932 Console 0 4,092 K . cmd.exe 3012 Console 0 2,860 K tasklist.exe 5888 Console 0 5,008 K C:\Documents and Settings\eric> 

The second column is the PID

You can use tasklist to get info on a specific PID:

Image Name PID Session Name Session# Mem Usage ========================= ====== ================ ======== ============ mysqld.exe 1300 Console 0 17,456 K C:\Documents and Settings\eric> 

A response means the PID is running.

If you query a PID that does not exist, you get this:

C:\Documents and Settings\eric>tasklist /FI "PID eq 1301" INFO: No tasks running with the specified criteria. C:\Documents and Settings\eric> 

A Java function could do the above automatically

This function will only work on Windows systems that have tasklist available.

import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class IsPidRunningTest < public static void main(String[] args) < //this function prints all running processes showAllProcessesRunningOnWindows(); //this prints whether or not processID 1300 is running System.out.println("is PID 1300 running? " + isProcessIdRunningOnWindows(1300)); >/** * Queries if the process ID is running. * @param pid the PID to check * @return if the PID is running, otherwise */ public static boolean isProcessIdRunningOnWindows(int pid)< try < Runtime runtime = Runtime.getRuntime(); String cmds[] = ; Process proc = runtime.exec(cmds); InputStream inputstream = proc.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String line; while ((line = bufferedreader.readLine()) != null) < //Search the PID matched lines single line for the sequence: " 1300 " //if you find it, then the PID is still running. if (line.contains(" " + pid + " "))< return true; >> return false; > catch (Exception ex) < ex.printStackTrace(); System.out.println("Cannot query the tasklist for some reason."); System.exit(0); >return false; > /** * Prints the output of including PIDs. */ public static void showAllProcessesRunningOnWindows()< try < Runtime runtime = Runtime.getRuntime(); String cmds[] = ; Process proc = runtime.exec(cmds); InputStream inputstream = proc.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String line; while ((line = bufferedreader.readLine()) != null) < System.out.println(line); >> catch (Exception ex) < ex.printStackTrace(); System.out.println("Cannot query the tasklist for some reason."); >> > 

The Java code above prints a list of all running processes then prints:

Читайте также:  Html style text box background color

Solution 3

boolean isStillAllive(String pidStr) < String OS = System.getProperty("os.name").toLowerCase(); String command = null; if (OS.indexOf("win") >= 0) < log.debug("Check alive Windows mode. Pid: [<>]", pidStr); command = "cmd /c tasklist /FI \"PID eq " + pidStr + "\""; return isProcessIdRunning(pidStr, command); > else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0) < log.debug("Check alive Linux/Unix mode. Pid: [<>]", pidStr); command = "ps -p " + pidStr; return isProcessIdRunning(pidStr, command); > log.debug("Default Check alive for Pid: [<>] is false", pidStr); return false; > boolean isProcessIdRunning(String pid, String command) < log.debug("Command [<>]",command ); try < Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(command); InputStreamReader isReader = new InputStreamReader(pr.getInputStream()); BufferedReader bReader = new BufferedReader(isReader); String strLine = null; while ((strLine= bReader.readLine()) != null) < if (strLine.contains(" " + pid + " ")) < return true; >> return false; > catch (Exception ex) < log.warn("Got exception using system command [<>].", command, ex); return true; > > 

Источник

Java check if exe is running

We use cookies to collect and analyze information on site performance and usage, to provide social media features and to enhance and customize content and advertisements.

Based on this HowTo which list the currently running processes, we adapt it to check for a specific program name.

In this example, we check if the text editor TextPad.exe is running.

import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.InputStreamReader; public class VBSUtils < private VBSUtils() < >public static boolean isRunning(String process) < boolean found = false; try < File file = File.createTempFile("realhowto",".vbs"); file.deleteOnExit(); FileWriter fw = new java.io.FileWriter(file); String vbs = "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n" + "Set locator = CreateObject(\"WbemScripting.SWbemLocator\")\n" + "Set service = locator.ConnectServer()\n" + "Set processes = service.ExecQuery _\n" + " (\"select * from Win32_Process where name='" + process +"'\")\n" + "For Each process in processes\n" + "wscript.echo process.Name \n" + "Next\n" + "Set WSHShell = Nothing\n"; fw.write(vbs); fw.close(); Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath()); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); String line; line = input.readLine(); if (line != null) < if (line.equals(process)) < found = true; >> input.close(); > catch(Exception e) < e.printStackTrace(); >return found; > public static void main(String[] args) < boolean result = VBSUtils.isRunning("TextPad.exe"); msgBox("Is TextPad running ? " + (result ? " Yes" : "No")); >public static void msgBox(String msg) < javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION); >>

Источник

Kurt-P / ProcessChecker.java

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

import java . io . BufferedReader ;
import java . io . InputStreamReader ;
/**
* @author Kurt P
* @version 2.5.12272012
*/
public class ProcessChecker
/**
* Checks if a specific process is running
*
* @param String application. The application to check for (Must have «.exe» at the
* end to distinguish applications which start with the same name.)
* @return true if process is found
*/
public boolean check ( String application )
//TODO: MAKE THIS DO A SWITCH STATEMETN INSTEAD OF A 4 IF STATEMENTS.
if ( checkOS (). contains ( «Windows» ))
try
String line ;
Process p = Runtime . getRuntime (). exec ( System . getenv ( «windir» )
+ » \\ system32 \\ » + «tasklist.exe» );
BufferedReader input = new BufferedReader (
new InputStreamReader ( p . getInputStream ()));
while (( line = input . readLine ()) != null )
if ( line . contains ( application )) < //Parsses the line
return true ;
>
>
input . close ();
>
catch ( Exception err )
Outputter . getInst (). error ( err );
>
return false ;
>
else if ( checkOS (). contains ( «Linux» ))
try
String line ;
Process p = Runtime . getRuntime (). exec ( «ps -e» );
BufferedReader input = new BufferedReader (
new InputStreamReader ( p . getInputStream ()));
while (( line = input . readLine ()) != null )
if ( line . contains ( application ))
return true ;
>
>
input . close ();
>
catch ( Exception err )
Outputter . getInst (). error ( err );
>
return false ;
>
else if ( checkOS (). contains ( «Mac OS» ))
try
String line ;
Process p = Runtime . getRuntime (). exec ( «ps -e» );
BufferedReader input = new BufferedReader (
new InputStreamReader ( p . getInputStream ()));
while (( line = input . readLine ()) != null )
if ( line . contains ( application ))
return true ;
>
>
input . close ();
>
catch ( Exception err )
Outputter . getInst (). error ( err );
>
return false ;
>
else
return false ;
>
>
/**
* @return A string containing the name of the operating system.
*/
private String checkOS ()
String os ;
os = System . getProperty ( «os.name» );
return os ;
>
>

Источник

Java – check if some exe program is running on the windows

How to check if some .exe program is running (is in process) on Windows?

I’m making java application which update one .exe program. So, if that exe program is used by some client, my application ask for closing exe program, and after closing automatically replace .exe file with new one.

Best Solution

You can run the following statement in your java program. Before that you need to know the name of the task in task manager . Say you want to see MS-Word is running. Then run MS-Word, go to task manager and under the process tab, you should see a process named word.exe . Figure out the name for the process you are targeting. Once you have that, you just run the following code:

String line; String pidInfo =""; Process p =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe"); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) < pidInfo+=line; >input.close(); if(pidInfo.contains("your process name")) < // do what you want >
Java – How to deal with “java.lang.OutOfMemoryError: Java heap space” error

Ultimately you always have a finite max of heap to use no matter what platform you are running on. In Windows 32 bit this is around 2GB (not specifically heap but total amount of memory per process). It just happens that Java chooses to make the default smaller (presumably so that the programmer can’t create programs that have runaway memory allocation without running into this problem and having to examine exactly what they are doing).

So this given there are several approaches you could take to either determine what amount of memory you need or to reduce the amount of memory you are using. One common mistake with garbage collected languages such as Java or C# is to keep around references to objects that you no longer are using, or allocating many objects when you could reuse them instead. As long as objects have a reference to them they will continue to use heap space as the garbage collector will not delete them.

In this case you can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place. One option which I have used in the past is «JMP» http://www.khelekore.org/jmp/.

If you determine that you are allocating these objects for a reason and you need to keep around references (depending on what you are doing this might be the case), you will just need to increase the max heap size when you start the program. However, once you do the memory profiling and understand how your objects are getting allocated you should have a better idea about how much memory you need.

In general if you can’t guarantee that your program will run in some finite amount of memory (perhaps depending on input size) you will always run into this problem. Only after exhausting all of this will you need to look into caching objects out to disk etc. At this point you should have a very good reason to say «I need Xgb of memory» for something and you can’t work around it by improving your algorithms or memory allocation patterns. Generally this will only usually be the case for algorithms operating on large datasets (like a database or some scientific analysis program) and then techniques like caching and memory mapped IO become useful.

Windows – Signing a Windows EXE file

You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:

This signs a single executable, using the «best certificate» available. (If you have no certificate, it will show a SignTool error message.)

This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)

If you’d like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool Makecert.

Once you’ve created your own certificate and have used it to sign your executable, you’ll need to manually add it as a Trusted Root CA for your machine in order for UAC to tell the user running it that it’s from a trusted source. Important. Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL. You can find more information for accomplishing this both in code and through Windows in:

Hopefully that provides some more information for anyone attempting to do this!

Related Question

Источник

Оцените статью