process continues to run after using Java exec - java

I have the following method
public static void disableMobileDate()
{
try
{
Runtime rt = Runtime.getRuntime();
Process pr = null;
pr = rt.exec("C:\\Program Files\\Android\\android-sdk\\platform-tools\\adb shell svc data disable");
System.out.println("### Data disabled on mobile device! ###");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Every time this method is ran from my program, it creates a adb.exe in task manager. The adb.exes (multiple adb.exe processes) stays there until I close my program. Is there anyway to make the process end after the command has been successfully executed?

You can call pr.destroy() after your command execution.
Or you can kill the process via the taskkill command:
rt.exec("taskkill /F /IM adb.exe")

You can kill the process by doing pr.destroy() to kill. But you should listen for the update that comes out, and once it prints what you are looking for, then you should kill it. A way to get the output is here.

Related

Collect environment variable in java after running script through ProcessBuilder

Why does the the following code print false ? I am trying to an environment variable in the test.sh script and collect it in java. Please suggest an alternative approach, if possible.
public static void main(String[] args){
ProcessBuilder processBuilder = new ProcessBuilder("test.sh");
Process process;
int exitCode;
try {
process = processBuilder.start();
exitCode = process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String>envVars = processBuilder.environment();
System.out.println(envVars.keySet().contains("SOURCE"));
}
And the code for test.sh script is simply
set SOURCE=source
The ProcessBuilder.environment() method is used for passing the initial environment to the process when you call start(). You cannot get the environment of a subprocess from a parent process. This is not a Java restriction: you can't even get a subprocess environment from a Bash shell script (or in fact anything) that creates a subprocess. You need to find another means of communicating information from the subprocess back to the parent process.
In my opinion, you should change:
ProcessBuilder processBuilder = new ProcessBuilder("test.sh");
to
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "test.sh");
processBuilder.directory(new File(the-dir-of-test.sh));

Execute spark-submit programmatically from java

I am trying to execute it via:
Process process = Runtime.getRuntime().exec(spark_cmd);
with no luck. The command ran via shell starts my application which succeeds. Running it via exec start a process which dies shortly after and does nothing.
When I try
process.waitFor();
it hangs and waits forever. Real magic begins when I try to read something from the process:
InputStreamReader isr = new InputStreamReader(process.getErrorStream());
BufferedReader br = new BufferedReader(isr);
To do so I start a thread that reads from the stream in a while loop:
class ReadingThread extends Thread {
BufferedReader reader;
Wontekk(BufferedReader reader) {
this.reader = reader;
}
#Override
public void run() {
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Application starts, does some stuff, and hangs. When I abort my application, spark application wakes up (??????????) and completes remaining work. Does anyone have reasonable explanation of what is happening?
thanks
You can send spark job as spark-submit with the help of java code with the help of SparkLauncher so you can go though below link and check it our
https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/launcher/SparkLauncher.html
One way is Spark launcher as told by #Sandeep Purohit
I'd offer shell script approach with nohup command to submit job like this...
This worked for me incase of mapreduce executions... same way you can
try for spark background jobs as well.
Have a look https://en.wikipedia.org/wiki/Nohup
"nohup spark-submit <parameters> 2>&1 < /dev/null &"
When ever, you get messages then you can poll that event and call this shell script. Below is the code snippet to do this...
/**
* This method is to spark submit
* <pre> You can call spark-submit or mapreduce job on the fly like this.. by calling shell script... </pre>
* #param commandToExecute String
*/
public static Boolean executeCommand(final String commandToExecute) {
try {
final Runtime rt = Runtime.getRuntime();
// LOG.info("process command -- " + commandToExecute);
final String[] arr = { "/bin/sh", "-c", commandToExecute};
final Process proc = rt.exec(arr);
// LOG.info("process started ");
final int exitVal = proc.waitFor();
LOG.trace(" commandToExecute exited with code: " + exitVal);
proc.destroy();
} catch (final Exception e) {
LOG.error("Exception occurred while Launching process : " + e.getMessage());
return Boolean.FALSE;
}
return Boolean.TRUE;
}
Moreover to debug
ps -aef | grep "your pid or process name"
Below command will list the open files opened by the process..
lsof -p <your process id >
Also, have a look at process.waitFor() never returns

Java: wait for exec process till it exits

I am running a java program in Windows that collects log from Windows events. A .csv file is created on which certain operations are to be performed.
The commands are execed and piped. How can I cause my Java program to wait until the process is finished?
Here is the code snippet I am using:
Runtime commandPrompt = Runtime.getRuntime();
try {
Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable #{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 '; ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
//I have tried waitFor() here but that does not seem to work, required command is executed but is still blocked
} catch (IOException e) { }
// Remaining code should get executed only after above is completed.
You need to use waitFor() instead of wait(). That way your thread will block until the executed command finishes.
I found the answer here Run shell script from Java Synchronously
public static void executeScript(String script) {
try {
ProcessBuilder pb = new ProcessBuilder(script);
Process p = pb.start(); // Start the process.
p.waitFor(); // Wait for the process to finish.
System.out.println("Script executed successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
This shall work. If not, specify WHAT exactly does not work
Runtime commandPrompt = Runtime.getRuntime();
try {
Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable #{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 '; ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
powershell.waitFor();
} catch (IOException e) { }
// remaining code

Running a batch file by java

I just wanted to run a batch file using java code in win7. I can run .exe files with the code but u know it doesn't work with a batch. Where is the problem? You know even cmd.exe doesn't start with that command. But I can run other exe files, I've tried some. The code is this (with try and catch is that): none of them worked!
Runtime.getRuntime().exec("cmd.exe /c demo.bat");
Runtime.getRuntime().exec("demo.bat");
i tried to do work with process and i wrote the code below. it retuened
java.lang.IllegalThreadStateException:process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at Test.Asli.main(Asli.java:38)
this is the code:
try{
Runtime rt = Runtime.getRuntime();
Process proc= rt.exec("C:\\Windows\\System32\\cmd.exe");
int b = proc.exitValue();
// int exitVal = proc.exitValue();
//System.out.println("Process exitValue: " + exitVal);}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Try the following:
String[] cmd = {"cmd.exe", "/c", "demo.bat");
Runtime.getRuntime().exec(cmd);
I always prefer splitting the command and the parameters myself. Otherwise it is done by splitting on space which might not be what you want.
Try this:
Runtime.getRuntime().exec("cmd.exe /c start demo.bat");
Use this:
try {
Process p = Runtime.getRuntime().exec("C:PATH/TO/FILE/yourbatchfile.bat");
} catch(Exception e) {
e.printStackTrace();
}
It even hides the annoying prompt window (if you want that)

What is a process_reaper thread in Java?

I'm getting hundreds of these process_reaper threads that build up over time in my application. Anyone have any idea what these may be? They seem to be in my use of Runtime.exec() however I'm destroying my process in a finally statement but they still show up
screen shot:
http://www.dropmocks.com/mBxM5
Process proc = null;
String line;
try {
logger.info("Trying to execute command " + Arrays.asList(command).toString().replace(",", ""));
proc = Runtime.getRuntime().exec(command);
} catch (IOException e) {
logger.info("IOException while trying to execute " + command);
return false;
} finally {
if(proc != null) {
proc.destroy();
}
}
I haven't seen this one myself so I searched a little; it seems a process reaper is related to the Linux kernel process management and is a daemon thread. It maintains the process state so that resources can be freed/released/collected on process termination and so on. This resource might help you. There is a mention on reapers in the final parts.
you must call process.waitFor() after exec and before destory (asy action)

Categories

Resources