0

I have a PHP application which executes a Java .jar file through shell_exec():

shell_exec("java jar myJarProgram.jar");

I have a need to determine if an instance this java program myJarProgram.jar is already running, because if it is not, then I can start it using the above PHP statement.

How can I do that?

Shy
  • 482
  • 5
  • 16

2 Answers2

1

You can use "jps" utility to grep your process with java

jps -mlvV | grep myJarProgram.jar
anteastra
  • 23
  • 5
1

jps is a good candidate for this, but please note that

To use the jps command-line tool you need to install a JDK.

Otherwise, you can parse the output of another shell_exec call that uses ps with the arguments you want in order to get the running processes: at this point you can check if the process is present.

$search_string = "[j]ava jar myJarProgram.jar"; $running = shell_exec("ps -A -ww | grep '$search_string'"); or similar.

If $running is empty, you can launch the jar.

Another option is to perform everything with a single shell_exec, both with commands concatanation (simple && and ||) or creating a .sh script and shell_executing that.

EDIT: According to the user comment, the script must work both for Windows and Linux. You can use the php PHP_OS predefined constant to check if it's Windows or Linux:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') etc....

If it's Linux, you can use the shell_exec as reported above. If it's Windows, you can change the shell_exec string using the tasklist Windows command. I don't know it, but there are already dedicated questions and answers like this one.

Lorenzo S
  • 1,375
  • 11
  • 23
  • What does `-ww` do? – Shy Aug 26 '18 at 15:54
  • And hey I need a solution which works for both Linux and Windows systems – Shy Aug 26 '18 at 15:55
  • @Shy This is the best description of its usage :) : -w Use 132 columns to display information, instead of the default which is your window size. If the -w option is specified more than once, ps will use as many columns as necessary without regard for your window size. – Lorenzo S Aug 27 '18 at 07:46