Home > Software design >  How can I kill a just started Java process in shell script?
How can I kill a just started Java process in shell script?

Time:01-09

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.

CodePudding user response:

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 ...)

CodePudding user response:

Two ways.

  1. use system. Exit() inbuilt function.

or

  1. 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
  • Related