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));
Related
I have this simple script where I execute a .jar file and I'd need its PID for killing it after the sleep command:
java -jar test.jar &> output.txt & pid=$! sleep 10
The problem is: the PID changes after the application gets fully launched, this pid I get in first place is not the same PID the application has after 10 seconds sleeping (I checked it using ps).
How can I track down the PID so that I can kill the fully launched application?
I've tried using pstree -p $pid but I get a long list of Java children processes and I thought there might be a better way to implement this other than getting every child process, extracting PID using grep and killing it, also because I'm not 100% sure this is working.
I found another solution using jps but I'd prefer use native linux commands for compatibility.
I don't necessarily need PID, using process name could be a way but I don't how to retrieve that either having only parent process' PID.
If you want to use process name, might run :
$ kill -9 $(ps aux | grep '[t]est.jar' | awk '{print $2}')
Options Details:
kill: sends a kill signal (SIGTERM 15: Termination) to terminate any process gracefully.
kill -9: sends a kill signal (SIGTERM 9:Kill) terminate any process immediately.
ps: listing all processes.
grep: filtering, [p] prevent actual grep process from showing up in ps results.
awk: gives the second field of each line, which is PID. (ps output : $1:user, $2:pid ...)
Two ways.
use system. Exit() inbuilt function.
or
redirect the pid number to a file and use later to kill the process.
Ex:-
java -jar test.jar &> output.txt & echo $! > pid-logs
cat pid-logs | xargs kill -9
I am trying to get ProcessId of the same process from which I am running the pgrep command. But the InputStream is returning null.
If we run command pgrep terminal from terminal in mac we cant get the processid of terminal. but if we run lsappinfo command in terminal and search for terminal it is there along with the processid.
I want to get processId of the same process from which I am running the command, Is there any other efficient way to get processId from process name like that of pgrep.
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?
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.
I'm trying to execute the following Command in Java in order to kill the spawned process of bash script which is executed through java :
kill $(pgrep -P $(pgrep -P 5537))
I'm using apache Commons Exec Commandline to build the Command but it's no different to using ProcessBuilder here. So here is what I have so far:
CommandLine cmdLine = new CommandLine("bash");
cmdLine.addArgument("-c");
cmdLine.addArgument("kill $(pgrep -P $(pgrep -P "+pid+"))");
I get the error
bash: $'kill 7940\n7941\n7942\n7943': Command not found.
Normally I would now try to get the newlines out of the Command but it also doesn't work to kill just a single process because then I get the error :
bash: kill 7980: Command not found.
One the one hand I need to use bash to use the variables and on the other hand I can't use it because kill can't be executed with it...
firstly kill -9 pidnumber
Why would you need the bash variables? when java gives you strings to store variables?
Thirdly why not try System.Runtime.getRuntime().exec() ?
Also do you have permissions to kill the task? tried sudo kill -9 pid?