Java launch bash script issue - java

I've seen many examples how to run bash script, I tried several and for some reason, my script fails in some functionality.
I have a script start_update_set_up that is runned by launcher:
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "Script directory:"$DIR
nohup bash -c $DIR/start_update_set_up > $DIR/logs/start_update_set_up.log &
echo "Laucher finish execution"
If I run launcher directly from bash - if works perfectly. But if I try to run it from Java, sleep and curl function fails. Moreover, Java waiting for some reason while my main script finish execution, that I do not want and that's why I implement launcher and that's why do I want to detach it from Java by nohup
I tried: apache executor:
executor.execute(commandLine, new DefaultExecuteResultHandler());
Where commandline is my launcher.
and runtime.
Runtime runtime = Runtime.getRuntime();
try { Process process = runtime.exec("./launcher"); } catch (IOException e) {
logger.error("ExecuteException at running update script");
e.printStackTrace();
}
What am I missing? How to detach bash from Java?

I can't test it at the moment, but I think your script should terminate with an exit statement, that may be why your java code is waiting.
As for the sleep and curl functions failure, we can't help you if you don't show them.

Related

Create a script to run multiple java jar in different terminal windows

I wrote an application in java that needs five players and a server.
I need to write a script that executes the jar of the server and of every single player in different terminal windows. How can I do?
I tried a script and worked but the jar opened in the same terminal window than I tried with xterm or konsole with flag --noclose but does not work (warning command: konsole not found)
#! /bin/sh
xterm --hold -e java -jar /Users/Marco\ 1/Documents/ing-sw-2019-Lentini-Marazzi-Marini/out/artifacts/server_jar/adrenalina.jar
for X in $(seq 5)
do
konsole --noclose -e java -jar /Users/Marco\ 1/Documents/ing-sw-2019-Lentini-Marazzi-Marini/out/artifacts/client_jar/adrenalina.jar gui
done
exit;
To run a process in the background from bash, you'll need to add an & to the end of your command, e.g.
java -jar /path/to/jar/my.jar &
Otherwise bash will wait until the command execution terminates.

JAVA getRuntime().exec used to execute powershell script, Start-Process -wait no longer works

I am trying to execute a powershell script from my java console app, I was able to get this working with the below command:
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd "+dir+" & start cmd.exe /k \"Powershell C:\\runscript.ps1 args\"",null,dir);
p.waitFor();
Inside my powershell script, i have the below snippet which gets called in a loop,
Start-Process -FilePath $RunLocation -ArgumentList $args -wait -NoNewWindow -RedirectStandardOutput $OutputFile
$output = Get-Content $OutputFile| out-string
if(!($output.toLower().contains("failed"){
Remove-Item $outLogFile
}
If I open command prompt, and copy exactly what I have in my exec(...) command, it runs great, however, when I run it in my Java application, it seems like the -wait in my powershell script is being ignored, and the next line (which is checking and removing logs) is run, I've even gone to the length of adding a sleep for a few seconds in my powershell just after the Start-Process, this works but I'm hoping there is a better way.
The error i am getting is in the powershell script is below (this only happens when ive run it from my Java app, the -wait waits foor the start process to finsih before continuing when run directly from command prompt..):
Remove-Item : Cannot remove item D:\adhoc\logs\2016-06\output38844448.out: The process cannot access the file
'D:\adhoc\logs\2016-06\output38844448.out' because it is being used by another process.
At C:\runscript.ps1:91 char:3
+ Remove-Item $OutputFile
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (D:\adhoc\log...4448.out:FileInfo) [Remove-Item], IOException
+ FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
Why is the -wait in my powershell script not working when I run it from my Java app using runtime().exec?

Execute mutli command lines in java

I need a multi command to bring the CMD to the root of the disc it runs on.
This is how the structure looks on the USB
\data
\data\commands
\Java
\Java\bin
App.jar
App.bat
This is how the "event" looks:
String command = "cmd /c cd\\data\\commands && wscript \"invisible.vbs\" \"Ready2Go.bat\"";
try {
Process p = Runtime.getRuntime().exec(command);
} catch (Exception e) {
e.printStackTrace();
}
This works perfekt when running App.jar file and "using" the java thats installd on the computer it self.
But when i try to run it with the java that i installd on the usb it will not work. (guide to install java on usb
app.bat file:
set Path=\Java\bin;%%Path%%
java -jar app.jar
So i need the a command to Leave the \java\bin dir. (for it is from there, I think the program is now running) and then run my command.
i have tried:
"cmd /c cd\\ && cd\\data\\commands && wscript \"invisible.vbs\" \"Ready2Go.bat\"
But without much luck.
I really hope you understand what I mean
write a startup batch start.bat like so
#echo off
rem change to this batch's folder
pushd "%~dp0"
set Path="%~dp0\Java\bin";%%Path%%
set JAVA_HOME=%~dp0\Java
java -jar App.jar
popd
and execute it as \data\commands\start.bat
Setting the current path of a process from java is done using ProcessBuilder and setting the directory-property. See a sample here
How to set working directory with ProcessBuilder

Java :Kill process runned by Runtime.getRuntime().exec()

I need to write a code,that
run unix process with Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
find PID of the process by executing command from java code lsof -t -i: MYPORT
and kill him by pid kill -9 PID ( also by executing command from java code)
and then execute others commands
BUT
if I execute this command by Runtime.getRuntime().exec() my program exits with exit code 137 - this means that when I run Runtime.getRuntime().exec("kill -9 PID") I kill process of My java programm, but not the program, that I run from code.
How can I kill ONLY the process that I run from code ?
P.S. maybe I should use ProcessBuilder ?
You can kill a sub-process that you have launched from your java application with destroy:
Process p = Runtime.getRuntime().exec("java -jar MyServerRunner -port MYPORT");
p.destroy();
Also note that it might make sense to run that other code in a separate thread rather than in a separate process.
you can use .exec("ps|grep <your process name>");, and then parse the result to get the PID, finally .exec("kill PID");
Therefore, your process is killed but android app still alive.
You can get pid with reflection in unix (I know it is a bad idea :)) and call kill;
Process proc = Runtime.getRuntime().exec(
new String[] {"java","-classpath",System.getProperty("java.class.path"),... });
Class<?> cProcessImpl = proc.getClass();
Field fPid = cProcessImpl.getDeclaredField("pid");
if (!fPid.isAccessible()) {
fPid.setAccessible(true);
}
Runtime.getRuntime().exec("kill -9 " + fPid.getInt(proc));

Shell Script Won't Run From Java Program

There are two things to note right off the bat....
The shell script runs fine manually
A simple shell script (echo hello) that I wrote runs fine through java
So I have a shell script that I'm attempting to run through a Java process.
File sqlF = new File("path to deploy script");
Process proc = rt.exec(sqlF + "/deploy.sh");
proc.waitFor();
System.out.println(proc.exitValue());
When I run this code I get an ambiguous return value of "1".
Here's the shell script (because I imagine the issue may stem from here):
#!/bin/bash
mysql -u XXXX -h XXXXX < XXXXX.sql
mysql -u XXXX -h XXXXX database < DEPLOY-HELPER.sql
Any ideas as to why this would not execute properly from Java?
If you want to run a shell script you must explicitly invoke the shell and pass it the name of the script as an argument, as in
bash /path/to/script/deploy.sh
Neither Runtime.exec() nor ProcessBuilder know how to execute shell scripts themselves, they only know how to execute binary executables.

Categories

Resources